简体   繁体   中英

Rails after_initialize

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?

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM