sql - Rails includes with conditions -
is possible in rails > 3.2 add conditions join statement generated includes
method?
let's have 2 models, person , note. each person has many notes , each note belong 1 person. each note has attribute important
.
i want find people preloading notes important. in sql be:
select * people left join notes on notes.person_id = people.id , notes.important = 't'
in rails, similar way using includes
(note: joins
won't preload notes) this:
person.includes(:notes).where(:important, true)
however, generate following sql query returns different result set:
select * people left join notes on notes.person_id = people.id notes.important = 't'
please, notice first resultset includes people , second 1 people associated important notes.
also notice :conditions deprecated since 3.1.
according guide active record querying
you can specify conditions on includes eager loading this
person.includes(:notes).where("notes.important", true)
it recommends use joins
anyway.
a workaround create association this
class person < activerecord::base has_many :important_notes, :class_name => 'note', :conditions => ['important = ?', true] end
you able this
person.find(:all, include: :important_notes)
Comments
Post a Comment