Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Route based on something different than ID

So currently I have something like /users/1/ when I want to view a user profile. How can I go through routes.rb to change that to /user/chiggins/ where chiggins is a unique username?

like image 942
Chiggins Avatar asked Oct 13 '11 19:10

Chiggins


2 Answers

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

like image 51
Sławosz Avatar answered Nov 07 '22 04:11

Sławosz


Another possibility to consider would be the friendly_id gem - https://github.com/norman/friendly_id

like image 45
someoneinomaha Avatar answered Nov 07 '22 03:11

someoneinomaha