The to_param method on your model is what gets called to generate the
ID for the URL.
So a simple solution is to just change that. Lets say your “Category”
model has a unique “slug” field. You could change it to this:
class Category
def to_param
self.slug
end
end
Then instead of finding by ID in your controller like this:
Category.find(params[:id])
You would need to find by slug:
Category.find_by_slug(params[:id])
That doesn’t require any changes to routes. I know there are gems that
do this (maybe a little more elegantly). But this is a quick way to
get it working with minimal changes, and without any extra gems. Just
make sure whatever field(s) you use for to_param are unique.
I am confused as to how I would modify the routes to only catch the
urls that have an integer id?
Either use a regex to match the parameter (and then send it to a
different controller action) or have a single controller action that
runs both find_by_permalink and find_by_id.
Either use a regex to match the parameter (and then send it to a
different controller action) or have a single controller action that
runs both find_by_permalink and find_by_id.
I have added this to the controller which seems to work well, as my
regex writing is weak.
Then get stronger! You don’t need a very sophisticated regex, and no
Ruby programmer can afford to be scared of regexes. http://www.rubular.com is your friend if you need help.
Regexes are an essential tool in anything involving string processing –
and that includes Rails routing. Don’t ignore them.
@article = Article.find_by_permalink(params[:id])
unless @article
@article = Article.find(params[:id])
end
That works, but you might want to move it to the model (perhaps in a
find_by_permalink_or_id method).
Either use a regex to match the parameter (and then send it to a
different controller action) or have a single controller action that
runs both find_by_permalink and find_by_id.
I have added this to the controller which seems to work well, as my
regex writing is weak.
@article = Article.find_by_permalink(params[:id])
unless @article
@article = Article.find(params[:id])
end
Thanks for the help. I really appreciate it.
Dan
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.