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!

3 Responses to “Routing in Rails with Unique Column Names”

  1. Luke Says:

    Or you can define the tp_param in the model.

    def to_param
    “#{name}”
    end

  2. zanev Says:

    Thanks Luke, I’ll look it up!

  3. mssmotorrd Says:

    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?


Leave a Reply