Question

I'm following a tutorial and per the code, I should be able to call the following wihtout error:

page = Page.find(1) # works
page.sections.size # Does not work

subject = Subject.find(1) # works
subject.pages.size # works

A section belongs_to a page, and a page belongs_to a subject. I'm trying to count the number of sections that are associated with the respective page (in this case, page :id => 1).

The error is Undefined Method but I'm not accessing a method, I'm accessing an instance variable. I've reviewed my models and controller, and there is no scope or declerations defined for subject.pages.size yet it works without complaint. I'm quite perplexed why it's not working for it's child, page.sections when I'm trying to do the same operation.

The diagnostic info (from CLI using pry) can be found here: http://pastebin.com/xKKvSPkz

DB Schema: http://pastebin.com/hiAhXGt8

Was it helpful?

Solution

Ensure that the relationship between page and section is defined:

class Page < ActiveRecord::Base
  has_many :sections
end

class Section < ActiveRecord::Base
  belongs_to :page
end

With this relationship the following should work as expected:

page = Page.find(1)
page.sections.size
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top