【问题标题】:Tagging system with relationships带有关系的标记系统
【发布时间】:2013-10-14 04:57:25
【问题描述】:

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

 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 > 显示带有“葡萄酒”标签且与意大利国家有关系的文章

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多