本文介绍了文本哈希上的 Rails3 fields_for:未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 rails3 表单,允许用户编辑答案列表,作为评估的一部分.
我使用 fields_for
循环来生成每个文本输入:
app/models/assessment.rb :
班级评估
app/view/assessments/new.html.erb:
<p>初始化答案:<%= @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 适当的问题,为简洁起见省略" %><br/><%@assessment.answers[item_id] = ""%>@assessment.answers[item_id] %>
<%结束%>
问题:fields_for
循环执行零迭代,没有字段被打印.
(尽管初始化答案:"显示正确:{"a"=>143, "b"=>42})
解决方案
这应该可以.本地测试.
<p>初始化答案:<%= @assessment.answers %></p><% @assessment.answers.each do |key, value|%><%= form.fields_for :answers, @assessment.answers[key] 做 |answer_fields|%><div class="field"><%= answer_fields.label 键 %><br/><%= answer_fields.text_field 键,:value =>值%>
<%结束%><%结束%>
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} )
解决方案
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 %>
这篇关于文本哈希上的 Rails3 fields_for:未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!