Rails3 fields_for on text Hash: not working as exp

2019-02-04 23:05发布

问题:

I have a rails3 form that allows the user to edit a list of answers, as part of an assessment.
I use a fields_for loop to generate each text input:

app/models/assessment.rb :

class Assessment < ActiveRecord::Base
  serialize :answers, Hash   # answers is a t.text field used to store all answers.
end

app/view/assessments/new.html.erb :

<p>Initialized answers: <%= @assessment.answers %></p>

<% item_counter = 0 %>
<% form.fields_for :answers do |answer_fields| %>
    <% item_id = "item" + item_counter.to_s %>
    <% item_counter = item_counter + 1 %>
    <div class="field">
      <%= answer_fields.label "the appropriate question, omitted for brevity" %>
      <br/>
      <% @assessment.answers[item_id] = "" %>
      <%= answer_fields.text_field item_id, :value => @assessment.answers[item_id] %>
    </div>
<% end %>

PROBLEM: The fields_for loop does zero iteration, no field gets printed.
( despite "Initialized answers:" showing correctly: {"a"=>143, "b"=>42} )

回答1:

This should do. Tested locally.

<p>Initialized answers: <%= @assessment.answers %></p>

<% @assessment.answers.each do |key, value| %>
  <%= form.fields_for :answers, @assessment.answers[key] do |answer_fields| %>
      <div class="field">
        <%= answer_fields.label key %>
        <br/>
        <%= answer_fields.text_field key, :value => value %>
      </div>
  <% end %>
<% end %>


回答2:

Turns Hash to OpenStruct object solved my problem.

<% form.fields_for :answers, OpenStruct.new(answers) do |answer_fields| %>
<% item_id = "item" + item_counter.to_s %>
<% item_counter = item_counter + 1 %>
<div class="field">
  <%= answer_fields.label "the appropriate question, omitted for brevity" %>
  <br/>
  <% @assessment.answers[item_id] = "" %>
  <%= answer_fields.text_field item_id, :value => @assessment.answers[item_id] %>
</div>