1

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?

1
  • try changing the name of your after_initialize function Commented Dec 12, 2013 at 19:20

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.