Rails: HABTM - find all records with no association
Asked Answered
J

1

9

I have 2 models (Workout, Equipment) in a has and belongs to many relationship. If I use Workout.find(:all, :joins => :equipment, :conditions => "equipment.id = 5") it works, but if I use Workout.find(:all, :joins => :equipment, :conditions => "equipment.id = null") it doesn't return the records with no association. Any ideas?

Jonis answered 1/7, 2012 at 3:23 Comment(2)
Rails join is an inner join. Check out Jamsi's answer for left outer join which will give you the "unassociated workouts".Honniball
possible duplicate of Rails habtm and finding record with no associationCartography
S
11

Give this a whirl;

Workout.joins("left join equipments e on workouts.id = e.workouts_id").where("e.id is null")
Shaggy answered 1/7, 2012 at 3:47 Comment(1)
rails 3 arel: Workout.joins(:equipments, Arel::Nodes::OuterJoin).where( Equipment.arel_table[:id].eq(nil) )Rafaellle

© 2022 - 2024 — McMap. All rights reserved.