Andy
Andy

Reputation: 10988

Reducing redundancy in Rails routes and url helper

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:

  1. Currently the following routes work fine: /article/:id/:action, /article/:id/:title with a condition that article cannot have titles edit, show, index, etc.
  2. I believe friendly_id is unnecessary here, since the routes contain :id explicitly.
  3. As I see, SO uses different routes for questions /question/:id/:title, /posts/:id/:action and for users /users/:id/:name, /users/:action/:id

Upvotes: 0

Views: 484

Answers (2)

user176060
user176060

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

Jeff Paquette
Jeff Paquette

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

Related Questions