控制器可以从rails app中的视图中获取文本字段,其中字段是从循环生成的:

时间:2013-08-11 14:48:27

标签: ruby-on-rails ruby-on-rails-3 erb

我的视图基本上是一个创建很多字段的循环,我想在按下商店评分按钮时将所有字段值存储到数据库,如何访问每个字段得分并将其存储在来自控制器的* save_scores *方法的正确 level.score 属性?:

<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
%>

1 个答案:

答案 0 :(得分: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 %>