Routing in Rails with Unique Column Names
April 25, 2009
A small question popped up while I working with rails today, I’m not sure how well this is documented and it seems fairly straight forward but I feel the urge to share it.
The question is this: how can I route using, instead of a unique id, a different column in a set of data.
Say, for example I have a table with the columns id and name and both are unique. The data contained in my table is:
| id | name |
|---|---|
| 1 | Fred |
The default routing would be as such:
http://localhost/users/1
But what I am after is this:
http://localhost/Fred
How is this done? After playing around here is what I came up with:
Open the routes.rb file and add the line:
map.connect ':name', :controller => 'users', :action => 'show'
So we are passing the parameter :name to our show action in the user controller. Now we need to modify our users_controller.rb to accept this parameter.
def show
@user = User.find_by_name(params[:name])
end
And that’s all there is to it. Look up the Ruby on Rails API for more information on the find_by_ function
I haven’t had much experiance with ruby on rails so if I have said something that may be a little misleading make sure you let me know!
April 25, 2009 at 7:08 pm
Or you can define the tp_param in the model.
def to_param
“#{name}”
end
April 26, 2009 at 4:44 am
Thanks Luke, I’ll look it up!
May 3, 2009 at 12:52 pm
It’s the first time I commented here and I must say you share us genuine, and quality information for bloggers! Good job.
p.s. You have a very good template for your blog. Where did you find it?