开发者

Rails3 fields_for on text Hash: not working as expected

开发者 https://www.devze.com 2023-03-18 00:18 出处:网络
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:

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 开发者_如何学JAVA"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} )


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 %>


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消