Newbie Question (belongs_to and has_many)

Hi All,

I am running from the console. I have two models i_test and
test_question. Model i_test has_many test_questions and test_questions
belong_to i_test

Example 1 below works fine, but when I wrap the same code into a member
function like in example 2, the test_questions don’t save. (and I can’t
figure out why). Thanks in advance for any help!

//////////////////////
Example 1: (saves without a problem)

@t = ITest.new
@q = TestQuestion.new
@t.test_questions << @q
@t.save

//////////////////////
Example 2: (will not save the test_questions)

@t = ITest.new
@q = TestQuestion.new
@t.add_question(@q)
@t.save

where add_question is defined as the following:

class ITest < ActiveRecord::Base
has_many :test_questions

def add_question(question)
@test_questions << question
end
end

where add_question is defined as the following:

class ITest < ActiveRecord::Base
has_many :test_questions

def add_question(question)
@test_questions << question
end
end

Try changing the member function to

def add_question(question)

self.test_questions << question

end

Mike H. wrote:

This seems to work. I guess test_questions is not an instance variable
in this case.

Exactly - this caught me out as well. It’s because an ActiveRecord
object (which you extended your class out of) doesn’t store the data as
instance variables - it makes a runtime connection to the database and
just sort of sees what’s in there, and acts as a conduit to it’s
corresponding table in the database (at least that’s how i understand
it)

So you need to refer to the variables of a runtime object, hence ‘self’.

has_many :test_questions

def add_question(question)
@test_questions << question
end

try this instead:

def add_question(question)
test_questions << question
end

‘test_questions’ is not an instance variable (words proceeded by @
signs), it is a method added by has_many.

Hope that helps,

Steve

This seems to work. I guess test_questions is not an instance variable
in this case.

class ITest < ActiveRecord::Base
has_many :test_questions

def add_question(question)
self.test_questions << question
end
end

Mike H. wrote:

Hi All,

I am running from the console. I have two models i_test and
test_question. Model i_test has_many test_questions and test_questions
belong_to i_test

Example 1 below works fine, but when I wrap the same code into a member
function like in example 2, the test_questions don’t save. (and I can’t
figure out why). Thanks in advance for any help!

//////////////////////
Example 1: (saves without a problem)

@t = ITest.new
@q = TestQuestion.new
@t.test_questions << @q
@t.save

//////////////////////
Example 2: (will not save the test_questions)

@t = ITest.new
@q = TestQuestion.new
@t.add_question(@q)
@t.save

where add_question is defined as the following:

class ITest < ActiveRecord::Base
has_many :test_questions

def add_question(question)
@test_questions << question
end
end