Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 有很多:通过与一对多的合作 轨道4.2 ruby 2.1_Ruby On Rails_Ruby On Rails 4_Model_Associations - Fatal编程技术网

Ruby on rails 有很多:通过与一对多的合作 轨道4.2 ruby 2.1

Ruby on rails 有很多:通过与一对多的合作 轨道4.2 ruby 2.1,ruby-on-rails,ruby-on-rails-4,model,associations,Ruby On Rails,Ruby On Rails 4,Model,Associations,我有两个非常基本的模型(产品和标签),通过另一个模型(标签)有很多关联 我有另一个模型(类别),与前面提到的模型(产品)有一对多的联系 问题: 如何在视图中显示具有特定产品类别的产品的标签列表 换句话说:是否可以列出特定类别产品的所有标签 型号: class Product < ActiveRecord::Base has_many :taggings has_many :tags, through: :taggings belongs_to :category, counte

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

我有另一个模型(类别),与前面提到的模型(产品)有一对多的联系

问题:

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

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

型号:

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
类产品
最快的方法是
分类\对象.产品.地图(&:标签).展平
。可以改进。:)


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

您可以将
产品标签
关联添加到
类别
类别:

class Category < ActiveRecord::Base
  has_many :products
  has_many :product_tags, -> { uniq }, through: :products
end
DB查询将与另一个示例非常相似

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