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?
Asked
Active
Viewed 4,188 times
9

Nick5a1
- 917
- 3
- 15
- 28
-
Rails join is an inner join. Check out Jamsi's answer for left outer join which will give you the "unassociated workouts". – Salil Jul 01 '12 at 16:20
-
possible duplicate of [Rails habtm and finding record with no association](http://stackoverflow.com/questions/7032194/rails-habtm-and-finding-record-with-no-association) – Geoff Lanotte Nov 23 '12 at 23:08
1 Answers
11
Give this a whirl;
Workout.joins("left join equipments e on workouts.id = e.workouts_id").where("e.id is null")

James
- 2,284
- 1
- 20
- 29
-
rails 3 arel: `Workout.joins(:equipments, Arel::Nodes::OuterJoin).where( Equipment.arel_table[:id].eq(nil) )` – equivalent8 May 16 '13 at 13:03