我有 4 个模型:Products
, Vendors
, Categories
, CategoryProducts
(加入模型)。
- 供应商有许多产品。
- 产品属于供应商。
- 一个产品有很多类别。
- 供应商通过产品有许多类别。
这就是我的模型现在的设置方式:
Vendor.rb
class Vendor < ActiveRecord::Base
attr_accessible :name, :description, :category_ids, :product_ids, :user_id
has_many :products, :dependent => :destroy
has_many :categories, :through => :products
belongs_to :owner, :class_name => "User",
:foreign_key => "user_id"
end
Product.rb
class Product < ActiveRecord::Base
attr_accessible :name, :description, :price, :vendor_id, :category_ids
belongs_to :vendor
has_many :category_products do
def with_categories
includes(:category)
end
end
has_many :categories, :through => :category_products
end
Category.rb
class Category < ActiveRecord::Base
attr_accessible :name, :product_ids, :category_ids
has_many :category_products do
def with_products
includes(:product)
end
end
has_many :products, :through => :category_products
end
的连接模型Product & Category
:
CategoryProduct.rb
class CategoryProduct < ActiveRecord::Base
attr_accessible :product_id, :category_id, :purchases_count
belongs_to :product
belongs_to :category
validates_uniqueness_of :product_id, :scope => :category_id
end
当我尝试在命令行上获取供应商的类别时,它会返回很多重复的结果——主要是因为它本质上是返回该供应商拥有的每个产品的类别。
这是一个示例,其中v = Vendor.first
:
1.9.3p194 :008 > v.products.count
(0.3ms) SELECT COUNT(*) FROM "products" WHERE "products"."vendor_id" = 10
=> 8
1.9.3p194 :009 > v.categories.count
(0.3ms) SELECT COUNT(*) FROM "categories" INNER JOIN "category_products" ON "categories"."id" = "category_products"."category_id" INNER JOIN "products" ON "category_products"."product_id" = "products"."id" WHERE "products"."vendor_id" = 10
=> 13
1.9.3p194 :010 > Category.count
(7.8ms) SELECT COUNT(*) FROM "categories"
=> 2
v.products.count
有些产品有多个类别,这就是和之间存在差异的原因v.categories.count
。
我如何才能v.categories.count
向我展示唯一数量的类别(在这种情况下,最大值是2
)?
谢谢。