开发者

Rails 3 - Customizing resourceful routes

I have resourceful routes set up for a blog (model name: Article).

I want to customize my resourceful route to point to

articles/show/title-of-my-article

Now I read through this:

http://edgeguides.rubyonrails.org/routing.html#cus开发者_Go百科tomizing-resourceful-routes

But it didn't seem to explain how to overwrite the params not just the :controller or :action. The thing is I could do a singular resource or match a GET request but I'd like to overwrite my resourceful routes so I can still use all the resource helpers (i.e. article_path(@article.title) ) etc.

Can Anyone help me out here, any and all help is much appreciated!


You should override the to_param method on your model:

class Article
  def to_param
    self.title
  end
end

If you want to get a little bit trickier you should read up on generating custom slugs.


In addition to jonni's answer.

Overwriting the to_param method will produce the title when you call the resource helpers like article_path(@article) and it will be passed as the params[:id] to the controller.

Thereafter you will need to find the article more or less manually, i.e. instead of doing

Article.find(params[:id])

You will need to do

Article.find_by_title(params[:id])

I don't remember if that one creates a NotFound exception if the record is not found as the find method do so in that case you will have to check manually if a record was found and raise the exception yourself if it were not in order to trigger the 404-page.

One problem with doing this is that the title might consist of characters that is not allowed or recommended in a URL, so a better approach would be to store a slug based on the title in the database and find it by that.

(You can create the slug automatically by having a filter in the Model and create it by title.parameterize)

Easiest would of course be to use one of the many gems and plugins that already takes care of these things.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜