How to do find() with includes() in Rails 3

Ruby on-RailsRuby on-Rails-3

Ruby 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question99milesView Question on Stackoverflow
Solution 1 - Ruby on-RailsRobert SpeicherView Answer on Stackoverflow
Solution 2 - Ruby on-Railsmind.blankView Answer on Stackoverflow
Solution 3 - Ruby on-RailsIvailo BardarovView Answer on Stackoverflow
Solution 4 - Ruby on-Railscoder_timView Answer on Stackoverflow
Solution 5 - Ruby on-RailsNadiyaView Answer on Stackoverflow