Ruby on rails 带关系的标签系统
我为我们的文章实现了一个标签系统Ruby on rails 带关系的标签系统,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-3.2,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 3.2,我为我们的文章实现了一个标签系统 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
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
在我的索引页上,我只显示与正确的regionparams(region\u id)
相关的文章,因此这很好。但是如何将地区和国家参数集成到“tagged_with”功能中
范例
/en/italy/umbria/articles/wines
>显示标有“wines”的文章,这些文章与umbria地区有关系
/en/italy/tuscany/articles/wines
>显示标记为“wines”且与托斯卡纳地区有关系的文章
/en/italy/articles/wines>显示标记为“wines”且与意大利国家有关系的文章您有两种选择:嵌套资源和使用动态分段。护栏导轨: 基本上你可以这样说:
# 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"
控制器:
def index
if params[:tag]
@articles = Article.tagged_with(params[:tag])
else
@region = Region.find(params[:region_id])
@article_region = @region.articles
end
end
#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