Ruby-on-rails – Getting undefined method for ActiveRecord::Relation

activerecordruby-on-rails

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

Best Solution

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])