Chiggins Chiggins - 7 months ago 7
Ruby Question

Rails Route based on something different than ID

So currently I have something like /users/1/ when I want to view a user profile. Dunno how easy or common of a question this is, I'm a bit of a Rails noob at this point, but how can I go through routes.rb to change that to /user/chiggins/ where chiggins is a unique username?

Thanks much!

Answer

You need is to override to_param method in User model:

class User
  def to_param
   username
  end
end

Then rails will use it automagically for routing. See http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-to_param