我为我们的文章实施了标记系统。
class Country < ActiveRecord::Base
has_many :articles
end
class Region < ActiveRecord::Base
has_many :articles
end
class Article < ActiveRecord::Base
belongs_to :region
belongs_to :country
def self.tagged_with(name)
Tag.find_by_name!(name).articles
end
end
物品管理员:
def index
if params[:tag]
@articles = Article.tagged_with(params[:tag])
else
@region = Region.find(params[:region_id])
@article_region = @region.articles
end
end
在我的索引页面上,我只显示与正确的区域params(region_id)
相关的文章,所以这样可以正常工作。但是,我如何在“tagged_with”功能中整合区域和国家参数?
示例
/en/italy/umbria/articles/wines
&gt;显示标有“葡萄酒”并与翁布里亚地区有关系的文章
/en/italy/tuscany/articles/wines
&gt;显示标有“葡萄酒”并与托斯卡纳地区有关系的文章
/ en / italy / articles / wines&gt;显示标有“葡萄酒”并与意大利国家有关系的文章
答案 0 :(得分:1)
您有两种选择:嵌套资源和使用动态细分。检查导轨指南:
http://guides.rubyonrails.org/routing.html#dynamic-segments
基本上你可以这样说:
# routes.rb, You should put this just before defining root path. Also test how it works with routes scopes/namespaces
get ':country/:region/articles/:tag', to: "articles#tagged_and_regional"
控制器:
#articles_controller.rb
def tagged_and_regional
Article.tagged_and_regional(params[:country], params[:region], params[:tag])
end
型号:
# I don't know Your data structure, so I am taking a guess
def self.tagged_and_regional(country, region, tag)
joins(:region, :country, :tags)
.where("counties.name = ? AND regions.name = ? AND tags.name = ?", country, region, name)
end