Rails 4 Query on Association using Includes

26 views
Skip to first unread message

mikej

unread,
Feb 17, 2016, 11:15:24 AM2/17/16
to Ruby on Rails: Talk

This works:


Model1.includes(:model2 => :model2).where(model2s: {order:  2})


How would I write a query for order <= 2?


What I would really like to write is:


Model1.includes(:model2 => :model2).where(“model2s.order <= 2”)


This worked in Rails 3, I would like to build up the where clause as a string.  Any ideas on how I can use a string to query an association in Rails 4 would be much appreciated.


Many thanks,


Mike

mikej

unread,
Feb 24, 2016, 9:21:12 AM2/24/16
to Ruby on Rails: Talk
I never worked this out, but you can use joins instead of includes as a work around.

mikej

unread,
Mar 4, 2016, 7:12:49 AM3/4/16
to Ruby on Rails: Talk
You can also use:

Model1.includes(:model2 => :model3).where(“model2s.order <= 2”).references(:model2 => :model3)
Reply all
Reply to author
Forward
0 new messages