Reputation: 3995
I have the following class:
class Question < ActiveRecord::Base
serialize :choices
attr_accessible :content, :choices, :answer_id
after_initialize :after_initialize
private
def after_initialize
choices ||= ['','','','']
end
end
The intent is that each question has 4 possible answer choices, and I want the question objects to always have those choices initialized, even if they are blank. They should never be saved to the database blank, but that's a separate issue. Anyway...
In my question form, I iterate through the choices:
<% @question.choices.each_with_index do |value, key| %>
<tr>
<td>
<%= f.radio_button :answer_id, key %>
</td>
<td>
<input name="question[choices][]" type="text" value="<%= value %>" />
</td>
</tr>
<% end %>
This should give the user 4 inputs to enter the answer choice text and radio buttons to choose which one is correct. When I load up the form to create a new question, I get this error:
undefined method `each_with_index' for nil:NilClass
So basically, the :choices
attribute is not getting initialized correctly. Indeed, inspecting @question
gives me this:
#<Question id: nil, content: nil, choices: nil, answer_id: nil, created_at: nil, updated_at: nil>
I would expect everything else to be nil, but I'm expecting :choices
to be ['','','','']
. Am I timing this wrong?
Upvotes: 1
Views: 545
Reputation: 29389
The following code from after_initialize
is updating the choices
local variable, which is not what you want:
choices ||= ['','','','']
You need to use
self.choices || = ['','','','']
as discussed in Why do Ruby setters need "self." qualification within the class?
Upvotes: 1
Reputation: 27779
You're close. When setting an attribute the name isn't enough. Prefix with self.
to make it work:
self.choices ||= ['','','','']
Using just choices
creates a local variable of that name rather than setting the attribute.
Upvotes: 2