[英]Getting Records Based on Count of Associated Model
我想使用如下的where語句:
BaseProduct.where(BaseProduct.products.count => 1)
這是行不通的。我得到了xyz類的未定義方法'products'。
在Rails控制台中,我可以
BaseProduct.first.products
並獲得良好的輸出。
如何獲得相關模型計數為1的記錄?
協會:
class BaseProduct < ActiveRecord::Base
has_many :products
end
class Product < ActiveRecord::Base
belongs_to :base_product
end
像這樣嘗試:
BaseProduct.select("base_products.*, COUNT(products.id) AS cp")
.joins("INNER join products ON products .base_product_id= products.id")
.group("products.base_product_id")
.having("cp > 1")
請嘗試這個
Product.select('base_product_id, count(base_product_id) as c').includes('base_product').group('products.base_product_id').having('c > 1')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.