0

我为我们的文章实施了一个标记系统。

 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> 显示带有“葡萄酒”标签且与翁布里亚地区有关的文章

/en/italy/tuscany/articles/wines> 显示带有“葡萄酒”标签且与托斯卡纳地区有关的文章

/en/italy/articles/wines > 显示带有“葡萄酒”标签且与意大利国家有关的文章

4

1 回答 1

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
于 2013-10-13T20:57:25.947 回答