Joseph Le Brech
Joseph Le Brech

Reputation: 6653

Getting undefined method for ActiveRecord::Relation

I have the following models

class Book < ActiveRecord::Base
  has_many :chapters
end

and

class Chapter < ActiveRecord::Base
    belongs_to :book
end

in /chapters/edit/id I get

undefined method `book' for #<ActiveRecord::Relation:0x0000010378d5d0>

when i try to access book like this

@chapter.book

Upvotes: 27

Views: 43990

Answers (4)

stevec
stevec

Reputation: 52218

I got a similar error

Books.chapters
NoMethodError: undefined method `chapters' for #<Book::ActiveRecord_Relation:0x00007f8f9ce94610>

what I needed was:

Books.includes(:chapters)

Upvotes: 0

Jason
Jason

Reputation: 450

As the others have said - adding the .first method will resolve this. I have experienced this issue when calling a @chapter by it's unique ID. Adding .first (or .take in Rails 4) will ensure only one object is returned.

Upvotes: 5

hellion
hellion

Reputation: 4830

Try: Chapter.find(params[:id]).first

Upvotes: 4

alony
alony

Reputation: 10823

Looks like @chapter is not a single Chapter object. If @chapter is initialized something like this:

@chapter = Chapter.where(:id => params[:id])

then you get a Relation object (that can be treated as a collection, but not a single object). So to fix this you need to retrieve a record using find_by_id, or take a first one from the collection

@chapter = Chapter.where(:id => params[:id]).first

or

@chapter = Chapter.find_by_id(params[:id])

Upvotes: 68

Related Questions