I have a rails3 form that allows the user to edit a list of answers, as part of an assessment.
I use afields_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.
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>
精彩评论