Reputation: 10988
I want to add article's title to its url similarly to SO URLs. I was suggested to use the following setup in answer to my another question
# routes.rb
match '/articles/:id/:title' => 'articles#show', :as => :article_with_title
# articles/index.html.erb
link_to article.title, article_with_title_path(article, :title => article.title.downcase.gsub(/[^a-z0-9]+/,' ').strip.gsub(/\s+/,'-'))
It works, however I find it a bit redundant. Is there a way to make it nicer? What about an additional universal method to handle multiple routes?
match '/articles/:id/:title' => 'articles#show'
match '/users/:id/:name' => 'users#show'
etc.
Remarks:
/article/:id/:action
, /article/:id/:title
with a condition that article cannot have titles edit, show, index, etc.
friendly_id
is unnecessary here, since the routes contain :id
explicitly./question/:id/:title
, /posts/:id/:action
and for users /users/:id/:name
, /users/:action/:id
Upvotes: 0
Views: 484
Reputation:
Just override to_param
in your models. Untested example from memory:
def to_param
self.id + "-" + self.name.parameterize
end
this approach means you don't have to change the router, and can also keep using Model.find(params[:id])
or similar.
Basically what the Railscast mentioned in another answer does, and the core of what friendly_id does too.
Upvotes: 1
Reputation: 7127
Ryan Bates did an excellent screencast on using the model's name, or any other attribute, in the url instead of the id.
Upvotes: 1