我的网址类似于http://example.com/posts/?tag=2
我的routes.rb
是
resources :posts do
get 'tag', :on => :collection
end
我需要像http://example.com/posts/tag/linux
我的表是:
posts(id,title)
tags(id,name)
taggings(id, post_id, tag_id)
答案 0 :(得分:2)
resources :posts do
get 'tag/:name', on: :collection
end
在您的控制器中,您可以在网址参数中找到带有名称的标记,并获取包含此标记的所有帖子。
Tag.where(name: params[:name]).posts
或者您在Post
模型中实施了一项功能find_by_tag(tag)
为您执行此功能,因此您只需致电
Post.find_by_tag(params[:name])
在你的控制者行动中,什么是更好的可读性。