在我的Rails型號我有:在Rails 3中,如何選擇items.join_model.id!= x的項目?
class Song < ActiveRecord::Base
has_many :flags
has_many :accounts, :through => :flags
end
class Account < ActiveRecord::Base
has_many :flags
has_many :songs, :through => :flags
end
class Flag < ActiveRecord::Base
belongs_to :song
belongs_to :account
end
我正在尋找一種方式來創建於宋模型,取不具有與其相關聯的定帳戶的歌曲範圍。
我已經試過:
Song.joins(:accounts).where('account_id != ?', @an_account)
但它返回一個空集。這可能是因爲有歌曲沒有帳戶附加到它?我不確定,但真的很苦惱這個。
更新
的結果集我正在尋找包括沒有與之相關的定帳戶的歌曲。這包括沒有標誌的歌曲。
感謝您的期待。
您可以發佈** Song.joins的SQL輸出(:帳戶)( '?ACCOUNT_ID ==',@an_account)。凡** – Gazler
我貼錯了代碼到我的問題。它應該是!=。但是,這裏是SQL輸出:'SELECT「歌曲。* FROM」歌曲「INNER JOIN」flags「ON」歌曲「。」id「=」flags「。」song_id「INNER JOIN」accounts「ON」accounts「。 「id」=「flags」。「account_id」WHERE(account_id!= 1)ORDER BY類型ASC,標題ASC' – jklina
你可以嘗試用includes(:accounts)替換連接(:accounts)嗎? – Gazler