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
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.
ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With