我使用counter_culture gem,但是当我想使用它时,它会抛出一个错误,它无法在Product模型中找到product_id字段,这是有道理的,因为它应该寻找'id'。
以下是我调用'Product.counter_culture_fix_counts'时生成的查询。正如您所看到的,它产生了'LEFT JOIN产品AS产品ON product_categories.id = products.product_id',这是不正确的,它应该是'LEFT JOIN产品AS产品ON product_categories.product_id = products.id'。
SELECT categories.id, categories.id, COUNT(products.id) AS count, categories.products_count FROM "categories" LEFT JOIN product_categories AS product_categories ON categories.id = product_categories.category_id LEFT JOIN products AS products ON product_categories.id = products.product_id AND (products.active = 't') GROUP BY "categories"."id" ORDER BY "categories"."id" ASC LIMIT 1000 OFFSET 0
以下是模特:
# Product Model
class Product
has_one :product_category, dependent: :destroy
has_one :category, :through => :product_category
counter_culture [:product_category, :category], :column_name => Proc.new { |product| 'products_count' }, :column_names => { ["products.active = ?", true] => 'products_count' }, :touch => true
end
# ProductCategory Model
class ProductCategory
belongs_to :product
belongs_to :category
end
# Category Model
class Category
has_many :product_categories, dependent: :destroy
has_many :products, :through => :product_categories
end
知道如何让这个工作吗? 谢谢你,米罗