Rails route to username instead of id
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
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
.
In the User model override the to_param
method to return what you want used in the URL.
class User < ActiveRecord::Base
def to_param
username
end
end
In your controller instead of using User.find(params[:id])
you now need to use User.find_by_username(params[:id])
You can use friendly_id gem: https://github.com/norman/friendly_id
You don't have to override to_param
if you don't want to, you can just specify in the form tag like this:
<%= form_for @user, :url => user_path(:id => @user.username) do |f|%>
精彩评论