I am trying to change the rails routes from /users/1 to /username. I currently set this up so it works for the actions of showing and editing. The actual issue is that when I go to update the user by using:
<%= form_for @user do |f|%>
It never updates, because the update action is routed to /users/:id. Is there any way to route this so that it works for /username? (which is the route that is rendering in my forms as the action). I've been scratching my head over this one for a while now.
EDIT:
The issue isn't routing to username, that it working correctly. The issue is that the form routes to /username for update, however the update route for users is still /users/:id instead of :/id.
I tried updating my routes to this, but to no avail:
match '/:id', :to => "users#show", :as => :user match '/:id', :to => "users#update", :as => :user, :via => :put match '/:id', :to => "users#destroy", :as => :user, :via => :delete
EDIT:
Doh! This fixed the issue:
match '/:id', :to => "users#show", :as => :user, :via => :get
You can specify what Rails should route '/' to with the root method: You should put the root route at the top of the file, because it is the most popular route and should be matched first. The root route only routes GET requests to the action. You can also use root inside namespaces and scopes as well. For example:
While the default routes and helpers generated by resources will usually serve you well, you may want to customize them in some way. Rails allows you to customize virtually any generic part of the resourceful helpers. The :controller option lets you explicitly specify a controller to use for the resource.
2 Resource Routing: the Rails Default. Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, a resourceful route declares them in a single line of code.
If you need to use a dot within an :id add a constraint which overrides this - for example id: / [^\/]+/ allows anything except a slash. The :as option lets you override the normal naming for the named route helpers.
In your user model:
def to_param username end
The to_param
method on ActiveRecord objects uses, by default, just the ID of the object. By putting this code in your model, you're overwriting the ActiveRecord default, so when you link to a User, it will use the username
for the parameter instead of id
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With