2014-02-17 38 views
1

Rails 3: 我在產品模型和配料模型之間有HABTM關係。我想從數據庫中刪除一堆孤兒成分,因此我需要查詢這些成分以刪除它們。我猜測有一個簡單的方法來做到這一點。有人能幫助我嗎?我預計今年的工作,但是我得到一個未定義的列錯誤HABTM孤立記錄 - 活動記錄查詢?

Ingredient.joins(:products).where(products: []) 

回答

1

here - >

這看起來是正確的:

Ingredient.joins('LEFT JOIN product_ingredients ON ingredients.id = product_ingredients.ingredient_id').where('product_ingredients.ingredient_id IS NULL').all 
1

products是最有可能也不的列的表。我認爲,像這樣的工作(假定產品具有name,與實際不存在的任何一列,否則更換):

Ingredient.joins(:products).where("products.name IS NULL") 
+0

這會引發錯誤。謝謝回覆。 – Brooks

0
Ingredient.all.map { | ingredient | ingredient.products.empty? } 

這應該映射的是有一個空的關係中的所有成分。你也可以嘗試:

Ingredient.all.map { | ingredient | ingredient.products.count > 0 } 

希望它有幫助!

+0

加載整個配料對象集太慢。感謝回覆。 – Brooks

0

找到了答案here

注意,SQL查詢做一個LEFT JOIN的連接表,在這種情況下, 'product_ingredients'

Ingredient.joins('LEFT JOIN product_ingredients ON ingredients.id = product_ingredients.ingredient_id').where('product_ingredients.ingredient_id IS NULL').all