作为评估的一部分,我有一个rails3表单,允许用户编辑答案列表.
我使用fields_for循环来生成每个文本输入:
我使用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”=> 143,“b”=> 42})
解决方法
这应该做.在本地测试
<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 %>