Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 699
Joseph Le Brech Avatar asked Jan 13 '12 09:01

Joseph Le Brech


People also ask

What is ActiveRecord :: Base in Rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is an ActiveRecord relation object?

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.

What is Ruby ActiveRecord?

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.


1 Answers

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]) 
like image 194
alony Avatar answered Sep 20 '22 06:09

alony