Shelby S
Shelby S

Reputation: 420

Rails .includes() returning 'undefined method'

I have a Company object with an associated Location.

Company has_many :locations Location belongs_to :company

When I call:

@company = Company.find(5).includes(:locations)

I get the error:

NoMethodError: undefined method `includes' for #<Company:0x000000066ad398>

I'm following the rubyonrails.org instructions to a T... as far as I can tell.

Upvotes: 3

Views: 2485

Answers (2)

Carlos Orellana
Carlos Orellana

Reputation: 184

Did you check the records in the database on location.rb model. The company_id is there?

You can use pry-rails in order to debug the code. Your code looks ok.

The json you are creating is with jbuilder? because is that the case, you need to create the corresponding each loop.

Upvotes: 0

Simone Carletti
Simone Carletti

Reputation: 176352

find() triggers a database query, and returns an instance of the model. You can't call includes on it, as includes is supposed to have an ActiveRecord::Relation as receiver.

You need to invert the order: find must stay at the end:

@company = Company.includes(:locations).find(5)

Upvotes: 9

Related Questions