Question

I am brand new to Ruby, and have just now touched upon associations. Here are my models:

class Subject < ActiveRecord::Base

  has_many :pages

  scope :visible, where(:visible => true)
  scope :invisible, where(:visible => false)
  scope :search, lambda {|query| where(["name LIKE ?", "%#{query}%"])}
end

class Page < ActiveRecord::Base

  belongs_to :subject
  has_many :sections
  has_and_belongs_to_many :editors, :class_name => "AdminUser"

end

My tutorial (psh.. what does it know) told me to type "subject.pages", after finding the first subject, like this:

Loading development environment (Rails 3.0.10)
irb(main):001:0> Subject.find(1)
=> #<Subject id: 1, name: "Initial Subject", position: 1, visible: true, created
_at: "2010-09-29 20:51:09", updated_at: "2010-09-29 21:07:42">
irb(main):002:0> subject.pages
NameError: undefined local variable or method `subject' for main:Object
        from (irb):2
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/comma
nds/console.rb:44:in `start'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/comma
nds/console.rb:8:in `start'
        from C:/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/comma
nds.rb:23:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'
irb(main):003:0>

According to the tutorial, it should have came back with an empty array. I have searched Google, this site, Yahoo Answers, everywhere for a possible explanation. Everything just seems to be correct to me. Can anyone help?

Was it helpful?

Solution

You need to store the result of Subject.find(1) into a variable before using it, just like you would with any language:

subject = Subject.find(1)

Then you can do subject.pages. Otherwise subject doesn't refer to anything.

Alternatively, you can use _ to refer to the return value of the last expression. So you could type Subject.find(1) and then _.pages.

If you're new to Ruby, though, I recommend going through this and perhaps this tutorial, and if you're feeling brave, this guide.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top