如何制作漂亮的网址

时间:2012-09-04 21:53:49

标签: ruby-on-rails routes slug

我的网址类似于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)

1 个答案:

答案 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])

在你的控制者行动中,什么是更好的可读性。