In Rails 3 how can I select items where the items.join_model.id != x? -


in rails models have:

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 

i'm looking way create scope in song model fetches songs not have given account associated it.

i've tried:

song.joins(:accounts).where('account_id != ?', @an_account) 

but returns empty set. might because there songs have no accounts attached it? i'm not sure, struggling one.

update

the result set i'm looking includes songs not have given account associated it. includes songs have no flags.

thanks looking.

am understanding question correctly - want songs not associated particular account?

try:

song.joins(:accounts).where(account.arel_table[:id].not_eq(@an_account.id)) 

answer revised: (in response clarification in comments)

you want sql conditions this:

song.all(:conditions =>   ["songs.id not in (select f.song_id flags f f.account_id = ?)", @an_account.id] ) 

or in arel, same sql generated this:

songs = song.arel_table flags = flag.arel_table  song.where(songs[:id].not_in(   flags.project(:song_id).where(flags[:account_id].eq(@an_account.id)) )) 

i prefer arel, , prefer in case too.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -