参数未被读取,即使它们似乎已被传递

时间:2014-06-19 00:05:12

标签: ruby-on-rails forms checkbox parameters

我正在创建一个为用户创建多条记录的表单,具体取决于用户决定使用复选框在表单中检查的项目数。

目前,我遇到param is missing or the value is empty: itemrecord的错误,即使在日志中,似乎params正在通过:

{"utf8"=>"✓", "authenticity_token"=>"m2NMruoFRr6lpsuVMK9UthlY0bsJsPmf1LWce2uKaH4=", ":item_name"=>["Backpack", "Water filter"], "commit"=>"Go!"}

模型关系是User has_many :inventories

控制器代码:

def create
    @itemrecord = @current_user.inventories.build

    items_to_be_saved = []
    inventory_params.each do |i|
        items_to_be_saved << ({ :signup_id => @current_user.id,  :item_name => i })
    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.require(:itemrecord).permit(:item_name)
end

查看代码:

          <%= form_for @itemrecord do |f| %>

            <!-- In case you're wondering, the @wishlist below is basically a hash of categories of items and items. This hash is updated in the controller, and then used by multiple views to create the same table of items. -->

            <% @wishlist.each do |category, list| %>
              <div class="col-xs-2">
                <div class="form-group box">
                  <h5> <%="#{category}"%> </h5>
                    <% list.each do |thing| %>
                        <%= check_box_tag ":item_name[]", "#{thing}" %>
                      </br>
                    <% end %>
                </div>
              </div>  
            <% end %>

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

          <% end %>

顺便说一下,我还尝试将:item_name更改为:item_names以根据我在SO上阅读的内容来解释数组,但这并没有解决它

1 个答案:

答案 0 :(得分:0)

查看您的inventory_params功能。您说您需要itemrecord,并且允许item_name属性。观察:

def inventory_params
  params.require(:itemrecord).permit(:item_name)
end

但是,在传递的参数中,没有任何对itemrecord对象的引用,但是引用了item_name。快速更改inventory_params方法,删除:itemrecord要求,而不是:item_name,将解决您的问题。

def inventory_params
  params.require(:item_name)
end

虽然这不一定是最好的方法(我建议您阅读Active Record Form Helpers),但它应该可以解决您的问题。