Re: [Rails-core] conditional eager loading

31 views
Skip to first unread message

Corey Haines

unread,
Oct 4, 2012, 7:37:45 PM10/4/12
to rubyonra...@googlegroups.com
Would merge work? Something like (off the top of my head):

Shift.includes(:schedules).merge(Schedule.occuring_on(Date.today))

where .occuring_on is

def self.occuring_on(day)
where(:occurs_on => day)
end

-Corey

On Thu, Oct 4, 2012 at 3:44 PM, r1git <erwan...@gmail.com> wrote:
> Does anybody know how to fix this issue:
> https://github.com/rails/rails/issues/4677 ?
>
> It seems so basic and yet there is no clean solution like conditional eager
> loading, something like:
>
> Shift.includes(:schedules).where(:schedules => { :occurs_on => Date.today })
>
> Or another solution would be threw a join request like:
>
> SELECT shifts.*,schedules.* from shifts LEFT JOIN schedules ON
> (schedules.shift_id = shifts.id AND schedules.occurs_on = Date.today);
>
> But using this in a Shift.joins("LEFT JOIN schedules ON (schedules.shift_id
> = shifts.id AND schedules.occurs_on = ?", Date.today) fails to return a
> properly filled Shift arrays. And any access to the Shift.schedules launch a
> new SQL request forgeting the occurs_on constraint...
>
> Thanks for any help
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby on Rails: Core" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/rubyonrails-core/-/tlvdnKOgj-cJ.
> To post to this group, send email to rubyonra...@googlegroups.com.
> To unsubscribe from this group, send email to
> rubyonrails-co...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/rubyonrails-core?hl=en.

r1git

unread,
Oct 5, 2012, 3:44:42 AM10/5/12
to rubyonra...@googlegroups.com
Thank you for your suggestion, I tested it and it launches the same SQL request as

Shift.includes(:schedules).where("schedules.occurs_on = '#{Date.today}'")
which fails to return the shifts with no schedules or schedules not matching the condition. Because the where apply on the whole SQL instead of the JOIN condition.
Reply all
Reply to author
Forward
0 new messages