Adding title to rails route

橙三吉。 提交于 2019-12-04 19:32:00

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.

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.

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

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