Rails3 fields_for on text Hash:无法按预期工作

时间:2011-07-08 07:32:48

标签: ruby-on-rails-3 activerecord erb

我有一个rails3表单,允许用户编辑答案列表,作为评估的一部分 我使用fields_for循环生成每个文本输入:

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

问题: fields_for循环执行零迭代,不打印任何字段。
(尽管“初始化答案:”正确显示:{“a”=&gt; 143,“b”=&gt; 42})

2 个答案:

答案 0 :(得分:18)

这应该做。在本地测试。

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

答案 1 :(得分:6)

将Hash转换为OpenStruct对象解决了我的问题。

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