How to do find() with includes() in Rails 3
Ruby on-RailsRuby on-Rails-3Ruby on-Rails Problem Overview
I'm trying to do something like this, but it's not working. How would I do this in Rails 3?
Student.find(12).includes(:teacher)
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
You just have to be more careful with the order of the methods in this case:
Student.includes(:teacher).find(12)
Solution 2 - Ruby on-Rails
Old question I know but just in case this helps someone...
Doing something like @student = Student.includes(:teacher).where(:id => 12)
returns an array and so then using something such as @student.id
doesn't work.
Instead you could do:
@student = Student.includes(:teacher).where(:id => 12).first
Although Student.includes(:teacher).find(12)
should work, but you can use the where
version if you need to search by other/multiple fields.
Solution 3 - Ruby on-Rails
Student.includes(:teacher).where(:id => 12)
should work.
Can we see your models ?
Solution 4 - Ruby on-Rails
You could try "where" instead of "find":
Student.includes(:teacher).where(:id => 12)
Solution 5 - Ruby on-Rails
There is no sense to use find
with includes
.
Eager loading helps us to load the associated records of the objects to prevent n+1 problem. With only one record you will never experience n+1 problem.