ruby-on-rails-3 – Rails3 fields_for文本哈希:不按预期工作

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-3 – Rails3 fields_for文本哈希:不按预期工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
作为评估的一部分,我有一个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”=> 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 %>
原文链接:/ruby/271036.html

猜你在找的Ruby相关文章