我有兩個模型產品和類別。檢索導軌關聯的反向多個記錄
我能做出這樣Category.products等
成功查詢Product.rb
belongs_to :category
Category.rb
has_many :products
現在我想找回只有那些至少有一個現有產品的類別。
我想是這樣的:
@categories = Category.where(Category.products.present?)
#返回的錯誤未定義的方法`產品也改變產品沒有工作。
Rails合併不會生成SQL UNION運算符。你的代碼等於next:Category.joins(:products).where(with_operator:true).uniq – 2014-10-06 14:40:00
而不是合併的意圖(閱讀文檔)。合併是告訴rails'with_operator'是產品表的條件,而不是類別表的條件。 – lcguida 2014-10-06 16:42:47
如果您運行'Category.joins(:products).where(with_operator:true).uniq'將返回一個錯誤,因爲rails會認爲'with_operator'是類別表 – lcguida 2014-10-06 18:01:42