Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails3 fields_for on text Hash: not working as expected

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} )

like image 734
Nicolas Raoul Avatar asked Jul 08 '11 07:07

Nicolas Raoul


2 Answers

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 %>
like image 80
awilkening Avatar answered Sep 26 '22 01:09

awilkening


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>
like image 34
wongyouth Avatar answered Sep 24 '22 01:09

wongyouth