【问题标题】:Parameters not being read even though they appear to be passed参数未读取,即使它们似乎已传递
【发布时间】:2014-06-19 00:05:11
【问题描述】:

我正在制作一个表单,根据用户决定使用复选框在表单中勾选的项目数量为用户创建多个记录。

目前,我遇到了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 上阅读的其他内容来解释数组,但这也没有解决它

【问题讨论】:

  • 将您的inventory_params 更改为此params.require(:inventory).permit(:item_name) 将起作用。
  • 根据@JKen13759 下面所说的,这也行不通
  • 你试过我的建议了吗?
  • @James 你最终尝试了我的答案吗?它对你有用吗?
  • 有点……我需要做一个params.permit[:item_name],但后来意识到我实际上需要一个全新的属性。但我喜欢你的回答,它确实有帮助,所以我接受了。

标签: ruby-on-rails forms checkbox parameters


【解决方案1】:

看看你的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),但它应该可以解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2012-05-30
    相关资源
    最近更新 更多