我有4个模型:Products
, Vendors
, Categories
, CategoryProducts
(连接模型)。
- 供应商有许多产品。
- 产品belongs_to供应商。
- 一个产品有多个类别。
- 供应商通过产品有许多类别。
现在我的模型是这样设置的:
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
)?
谢谢。
我认为这相当简单。只需使用uniq
方法,如下所示。
v.categories.uniq.count
要将其置于关联级别,可以使用:uniq => true
选项,如下所示。
has_many :categories, :uniq => true