I'm building currently one Rails app and I'd like to stick to all those fancy things like REST and Resources, but I'd like to customise my routes a little. I want my GET route to be little more verbose - the app I'm creating is a simple blog, so instead of GET /posts/1
I'd prefer something like GET /posts/1-my-first-post
.
Any ideas how to do this? Didn't find anything on the web.
Routes:
map.resources :posts
Model:
class Post < ActiveRecord::Base
def to_param
"#{id.to_s}-#{slug}"
end
end
Should do the trick.
Define a to_param
method in your Model and all the url helpers will youse what you return with that method, eg:
class Post < ActiveRecord::Base
der to_param
slug
end
end
You will also need to adapt your controllers for that. Replace:
Post.find(params[:id])
with:
Post.find_by_slug(params[:id])
Also note that the find method raises ActiveRecord::RecordNotFound exception when the record can't be found while using the find_by_* method no Exceptions will be raised so you need to check that manually.
您可以找到friendly_id插件很有用,因为它还可以处理重定向,如果您重命名slug(因此seo友好),处理名称冲突并与find方法无缝集成,因此您不需要触摸您的控制器方法(重定向除外)啄)。
Alternatively...
Add a method like this to application_helper.rb
def permalink(post)
"#{post_path(post)}-#{post.slug}"
end
Then use the following in your views (using permalink(@post)
instead of post_path
)
<%= link_to @post.title, permalink(@post) %>
Alternatively...
Add a method like this to post.rb
def path
"/posts/#{id}-#{slug}"
end
Then use the following in your views:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.