Number_field_tag为每个项目/数量创建唯一记录

时间:2014-06-19 17:55:28

标签: ruby-on-rails forms parameters strong-parameters form-helpers

我正在使用number_field_tag来允许用户指出他们拥有的给定项目的数量。然后,对于每个项目,应在模型中创建新记录。所有项目字段的默认数量为0.

我对如何使params适当传递(即如何编写强参数和表单代码)感到有点困惑。我写的控制器代码假定我会得到一个如下所示的哈希:

itemrecord = {
  "tent" => 1
  "sleeping bag" => 0
  ...
}

然后,我可以使用以下create代码创建记录(其中:item_name是模型Inventory的属性):

items_to_be_saved = []
   inventory_params.each do |item, quantity|
      quantity.times do
         items_to_be_saved << ( :item_name => item )
      end
   end

目前我在下面的视图/强参数代码产生了以下输出,这与我需要的不同,:item_record是一个数量数组,没有选择相关项。

Parameters: {"utf8"=>"✓", "authenticity_token"=>"m2NMruoFRr6lpsuVMK9UthlY0bsJsPmf1LWce2uKaH4=", ":itemrecord"=>["", "", "", "", "", "", "", "", "2", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], "commit"=>"Go!", "method"=>"post"}

表格代码

          <%= form_tag inventories_path method: :post do %>

            <div class="col-xs-12">
              <p><b>Items people are asking for</b></p>
            </div>

            <% @wishlist.each do |category, list| %>
              <div class="col-xs-2">
                <div class="form-group box">
                  <h5> <%="#{category}"%> </h5>
                    <% list.each do |thing| %>
                        <%= number_field_tag ":itemrecord[]", "#{thing}", {:size => 1, :placeholder => '0', :min => 0} %>
                        <%= label_tag "#{thing}" %>
                      </br>
                    <% end %>
                </div>
              </div>  
            <% end %>

              <%= submit_tag "Go!", class: "btn btn-primary btn-large btn-block" %>
            </div>
          <% end %>

控制器代码

def inventory_params
  params.require(":itemrecord")
end

修改!我有一个解决方案!但params部分非常hacky,需要更新。这是有效的代码:

查看

<%= number_field_tag "#{thing}", :quantity, min: 0, placeholder: 0 %>

控制器

def create

items_to_be_saved = []
inventory_params.each do |item, quantity|
  quantity = quantity.to_i
  quantity.times do
    items_to_be_saved << ({:signup_id => @signup_parent.id, :item_name => item })
  end
end

if Inventory.create items_to_be_saved
    flash[:success] = "Thanks!"
    redirect_to root_path
else
    render new_inventory_path
end

end

def inventory_params
    params.except(:action, :controller, :method, :commit, :utf8, :authenticity_token)
end

问题是让params.except违背了“强”参数的目的。我基本上需要将参数传递给控制器​​定义的任何一个项目清单。与表单类似,控制器代码为

def wishlist
    @wishlist = {
        "Category1" => ["ItemA", "ItemB"],
        "Category2" => ["ItemC", "ItemD"],
    }
end

正如您在视图中看到的那样,ItemAItemBItemCItemD是生成的每个表单字段的名称,以及参数的关键字hash(:quantity为值)。问题是如何允许它。以下内容不适用于错误:undefined method []'代表nil:NilClass on the permit`行

def inventory_params
  @wishlist.each do |category, list|
    list.each do |thing|
      params.permit[thing][:quantity]
      params.reject { |k, v| v == "" }
    end
  end
end

1 个答案:

答案 0 :(得分:0)

好的,我解决了。而且我意识到这很简单......当你工作太久时会发生这种情况......大脑停止了

控制器代码:

def create

    items_to_be_saved = []
    inventory_params.each do |item, quantity|
      quantity = quantity.to_i
      quantity.times do
      items_to_be_saved << (:item_name => item )
    end
end

if Inventory.create items_to_be_saved
    flash[:success] = "Thanks!"
    redirect_to root_path
else
    render new_inventory_path
end

end

def inventory_params
    params.permit[:quantity]
    params.reject { |k, v| v == "" }
end

查看代码:

          <%= form_tag inventories_path method: :post do %>

            <div class="col-xs-12">
              <p><b>Items people are asking for</b></p>
            </div>

            <% @wishlist.each do |category, list| %>
              <div class="col-xs-2">
                <div class="form-group box">
                  <h5> <%="#{category}"%> </h5>
                    <% list.each do |thing| %>
                        <%= number_field_tag "#{thing}", :quantity, min: 0, placeholder: 0 %>
                        <%= label_tag "#{thing}" %>
                      </br>
                    <% end %>
                </div>
              </div>  
            <% end %>

              <%= submit_tag "Go!", class: "btn btn-primary btn-large btn-block" %>
            </div>

          <% end %>