views:

25

answers:

3

I have a HABTM relationship between Videos and Campaigns in Rails which means the association is stored in a join table. I want to find all the Videos that do NOT have an associated campaign. What would be the most efficient way of doing this?

Thank you for looking =)

+1  A: 
Video.all(:include => :campaigns, :conditions => ["campaigns.id IS ?", nil])

the :include will do a left join to the associated table so anything without a campaign should have NULL values for the campaign field values.

Geoff Lanotte
A: 

The SQL way:

Videos.select_by_sql("SELECT * FROM videos WHERE id NOT IN (SELECT video_id FROM campaign_videos)")
Jamie Wong
Although why would you want to write pure sql in an environment which provides you the tools and the means to not do it,
Tanel Suurhans
A: 

The Ruby way:

Video.all.select {|v| v.campaigns.empty?}

I think this is more elegant if you use it standalone in a method. However, I would recommend to write a named scope for that. Then again, Geoffs version is the right one:

named_scope :campaign_less, :include => :campaigns, :conditions => ["campaigns.id IS ?", nil]

Besides, Geoffs solution is probably more efficient as it is more lowlevel.

duddle