Rails and SEF URLs: Changing the key used in link_to to use a different field then the primary key

314 Views Asked by At

In my Rails 3 app, I have a model called User with id and username, both are indexed and unique. Somewhere in some views I have following:

<%= link_to 'Show this user', user %>

That creates a link like this:

<a href="/users/980190962">Show this user</a>

where that horrible number is the id (primary key). Now, for the SEFness of the site, I would like to use the username instead of the id wherever I use link_to "...", user, but only for that User model. Adding parameters to the link_to does not help, because I already have it in many places (and I do not want to have to add another parameter everywhere all the time).

How can I override the behavior of the link_to helper only for one model?


Here is a complete answer to this question, as I deducted from the accepted answer. I added following to my User model:

def to_param  # overridden to use username as id, and not the id. More SEF.
  username
end
def self.find(id)
  @user = User.find_by_id(id)
  @user = User.find_by_username(id) if @user == nil
  throw ActiveRecord.RecordNotFound.new if @user == nil
  @user
end

This now makes all links generated with link_to use the username, while the find will try both the id and the username, making it also backward compatible.

Thought someone as new as me to Rails would find this useful.

1

There are 1 best solutions below

1
On BEST ANSWER

Not sure of what I'm saying, but overriding #to_param in your model may be what you're looking for.