如何使用rails中的一个表单更新多个字段

时间:2015-06-05 12:39:25

标签: ruby-on-rails

我想每天更新我的股票支票。所以我在我的数据库中有成分表也有IngredietnStockChek每天我想保存我的库存检查。 我的想法是创建一个表格,它会显示我已经获得的每件产品的输入字段数量,然后在这个表格上我会说明我有多少。

    <%= form_for(@stock_of_ingredient, :multipart => true,  html: { class: "form-horizontal", role: "form" }) do |f| %>
<% @ingredients.each do |b| %>
<%= fields_for "stock_of_ingredients" do |c| %>
 <div class="form-group">
    <%= c.label "#{b.name}", class: "col-sm-2 control-label" %>
    <div class="col-sm-10">
      <%= c.number_field :ingredient_id, class: "form-control", value: "#{b.id}" %>
    </div>
  </div>
  <div class="form-group">
    <%= c.label :quantity, class: "col-sm-2 control-label" %>
    <div class="col-sm-10">
      <%= c.text_field :quantity, class: "form-control" %>
    </div>
  </div>
  <div class="form-group">
    <%= c.label :todays_date, class: "col-sm-2 control-label" %>
    <div class="col-sm-10">
      <%= c.date_select :todays_date, class: "form-control" %>
    </div>
  </div>
<% end %>
<% end %>   

所以这是我的表格,我应该使用

 <%= fields_for "stock_of_ingredients" do |c| %>`

或者我应该

 <%= fields_for "stock_of_ingredients[]" do |c| %>

捕获所有字段的所有数据

如何修改控制器创建动作以保存所有,我应该使用循环但是如何。

 def create


    @stock_of_ingredient = StockOfIngredient.new(stock_of_ingredient_params)
    respond_to do |format|
      if @stock_of_ingredient.save

        format.html { redirect_to @stock_of_ingredient, notice: 'Stock of ingredient was successfully created.' }
        format.json { render :show, status: :created, location: @stock_of_ingredient }
      else
        format.html { render :new }
        format.json { render json: @stock_of_ingredient.errors, status: :unprocessable_entity }
      end
    end
  end

1 个答案:

答案 0 :(得分:3)

据我了解你在做什么,我认为你可以使用fields_for:

<%= form_tag update_my_ingredients_for_a_product_path, method: :put do %>
  <% @ingredients.each do |b| %>
    <%= fields_for "ingredients[]", b do |f| %>
     <div class="form-group">
       <%= f.label "#{b.name}", class: "col-sm-2 control-label" %>
       <div class="col-sm-10">
       <%= f.number_field :ingredient_id, class: "form-control", value: "#{b.id}" %>
       </div>
     </div>
     ...
  <% end %>
  <%= submit_tag "Save", class: "btn btn-default" %>
<% end %>

Documentation for fields_for

Railscast close to your question