polomasta wrote:
I’ve been reading everything about routes but I can’t seem to make
this work…
I have a projects controller and my projects table contains id and
name fields
I want to be able to navigate to myurl.com/projects/“name” instead of
the default method or /projects/“id”
Seems like this should be pretty basic but I haven’t been able to get
it to work.
Appreciate the help.
The most common way to do this is to override the to_param method on
your model. When rails generates a route for a model it calls to_param
on that model object, which ends up in the :id spot on your url. By
default, this returns the id.
If you add something like this to your model, where permalink is a
database field on that model:
def to_param
permalink
end
Then when you generate routes for that model object it will look like:
/thingies/my_cool_permalink
Now you just need to change how you fetch your models. On your show
action, change the standard
@thingy = Thingy.find(params[:id])
to
@thingy = Thing.find_by_permalink(params[:id])
One last popular way to handle this a hybrid approach. If you set your
to_param method to return something like:
“#{id}-#{permalink}”
Then you url will generator like:
/thingies/123-my_cool_permalink
#controller goes back to:
Thingy.find(params[:id])
The neat thing about this approach is that the ActiveRecord will convert
your params[:id] to an integer for you. This means that
“123-my_cool_permalink” gets translated to 123 without any extra code
from you. As an added bonus, the permalink part can change to something
new, and as long as the page is accessed by the same id number the link
wont break.