Adding title to rails route

我只是一个虾纸丫 提交于 2019-12-22 01:16:39

问题


I have List objects which are shown like this:

www.mysite.com/lists/123

Where 123 is the id of the list. What I would like to do is add the title of the list the url so it it more informative(for google or whatever). So I would like it to look like:

www.mysite.com/lists/123/title-of-list-number-123

How do you go about adding to a url like this? If you just enter: www.mysite.com/lists/123 w/o the title, should it find the title and then redirect to a new route?


回答1:


If you want to keep your find-calls as they are (by id), you could do the opposite of what mplacona suggested:

def to_param
  "#{id}-#{title.parameterize}"
end

With this, your find(params[:id]) will work because it'll convert the string to an integer (can only succeed if the number is in the beginning of the string). So this is will actually work:

List.find("123-my-title")

and will be the same as

List.find(123)

Read more about this and other ways to accomplish this here: http://gregmoreno.ca/how-to-create-google-friendly-urls-in-rails/

The parameterize will automatically convert the string to a "pretty" url. Read more here: http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html#M001367

If you want a bit more functionality, I'll suggest friendly_id aswell.




回答2:


This article says exactly what you need to do accomplish this.

http://railscasts.com/episodes/63-model-name-in-url

UPDATE

Have a permalink added to your model, and save as follow to it:

def to_param
  "#{permalink}-#{id}"
end

On your controller, instead of getting things by the id, get them by the pemalink:

@product = Product.find_by_permalink(params[:id])

And that's all you need.

The screen cast explains all the steps on how to do it.




回答3:


You could also take a look at friendly id, if you're in the mood for a gem/plugin.



来源:https://stackoverflow.com/questions/2410652/adding-title-to-rails-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!