【问题标题】:has_many :through Association working with one-to-manyhas_many :通过关联与一对多合作
【发布时间】:2015-05-20 04:05:16
【问题描述】:
  • 导轨 4.2
  • 红宝石 2.1

我有两个非常基本的模型(产品和标签),通过另一个模型(标签)与 has_many 关联。

我有另一个模型(类别)与上述模型(产品)具有一对多连接。

问题:

如何在视图中显示具有特定产品类别的产品的标签列表

换句话说:是否可以列出来自特定产品类别的所有标签?

型号:

class Product < ActiveRecord::Base
  has_many :taggings
  has_many :tags, through: :taggings
  belongs_to :category, counter_cache: true
end

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :products, through: :taggings
end

class Tagging < ActiveRecord::Base
  belongs_to :product
  belongs_to :tag, counter_cache: :products_count
end

class Category < ActiveRecord::Base
  has_many :products
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 model associations


    【解决方案1】:

    您可以将product_tags 关联添加到Category 类:

    class Category < ActiveRecord::Base
      has_many :products
      has_many :product_tags, -> { uniq }, through: :products
    end
    

    当您访问 product_tags 关联时,Rails 将使用 SELECT DISTINCT 查询,因此您不会得到重复的标签,并且数据库将消除重复。

    如果您的模型觉得以上内容不自然,那么您也可以使用以下内容(假设 cCategory 实例):

    Tag.joins(:products).where(products: { category: c})
    

    数据库查询与其他示例非常相似。

    【讨论】:

      【解决方案2】:

      最快的方法是category_object.products.map(&amp;:tags).flatten。可以改进。 :)

      类别有很多产品,产品有很多标签。在每个产品上映射标签方法。展平以删除重复项。

      【讨论】:

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