0

my view is basically a loop creating a lot of fields, I want to store all field values to database when the button Store Scores is pressed, how can I access each fields score and store it in the right level.score attribute from the controller's *save_scores* method?:

<p>Found : <%= @levels.length%> levels.</p>
<h2>Score board:</h2>
<% @levels.each do |level|%>
    <%= form_for(level) do |f| %>
        <% if level.errors.any? %>
            <div id="error_explanation">
              <h2><%= pluralize(level.errors.count, "error") %> prohibited this level from being saved:</h2>

              <ul>
                <% level.errors.full_messages.each do |msg| %>
                    <li><%= msg %></li>
                <% end %>
              </ul>
            </div>
        <% end %>

        <div class="field">
          <%= f.text_field :score %>
        </div>
        <div class="actions">
          <!--<%= f.submit %>    -->
        </div>
    <% end %>

<%end%>
<%= button_to "Store Scores",
              :action => 'save_scores',
              :id =>@game
%>
4

1 回答 1

1

在 Rails Recipe (2012) 一书中,我认为有一个食谱适合你的目的。

诀窍 36 为多个模型创建一个表格

Class Recipe < ActiveRecord::Base
  has_many :ingredients
  accepts_nested_attributes_for :ingredients
end

Class Ingredient < ActiveRecord:Base
  belongs_to :recipe
end

添加食谱

<%= form_for @recipe do |f| %>
  <%= f.label :name %> <%= f.text_field :name %>

  <%= f.label :instructions %> <%= f.text_area :instructions %>

  <%= f.fields_for(:ingredients) do |ingredients_form| %> 
    <%= ingredients_form.label :name %> 
    <%= ingredients_form.text_field :name %> 
    <%= ingredients_form.label :quantity %> 
    <%= ingredients_form.text_field :quantity %> 
  <% end %>

  <%= f.submit %> 
<% end %>
于 2013-08-11T15:35:25.083 回答