更新未采用表单提交中的所有参数

时间:2019-06-10 04:50:55

标签: ruby-on-rails ruby

提交表单时,我将看到以下内容:

Started PATCH "/shop_products/12" 
---
INFO -- : [f51ce4b8-f181-4da5-919a-01c99c703762] Processing by ShopProductsController#update as HTML
---
INFO -- : [f51ce4b8-f181-4da5-919a-01c99c703762]   Parameters: {"utf8"=>"✓", "authenticity_token"=>"xkByz5wY7x9ZBEcGPawvrrlsDsDSThX3mEBl09qZU7x+OEHSRvryGV1tS520hGAL3bihE1C/c1xnIoDhzocRTw==", "shop_product"=>{"product_id"=>"1", "store_product_id"=>"1965852983345", "store_variant_id"=>"15345629364273", "shop_id"=>"1", "sync"=>"true"}, "commit"=>"Sync", "id"=>"12"}
---
DEBUG -- : [f51ce4b8-f181-4da5-919a-01c99c703762]   [1m[36mShopProduct Load (1.9ms)[0m  [1m[34mSELECT  "shop_products".* FROM "shop_products" WHERE "shop_products"."id" = $1 LIMIT $2[0m  [["id", 12], ["LIMIT", 1]]
---
DEBUG -- : [f51ce4b8-f181-4da5-919a-01c99c703762]   [1m[36mShopProduct Load (3.3ms)[0m  [1m[34mSELECT  "shop_products".* FROM "shop_products" WHERE "shop_products"."store_variant_id" = $1 LIMIT $2[0m  [["store_variant_id", IS NULL LIMIT $1], ["LIMIT", 1]]
---
Completed 404 Not Found in 21ms (ActiveRecord: 8.3ms)
---
ActiveRecord::RecordNotFound (Couldn't find Product without an ID):

方法:

def update
    @shop_product = ShopProduct.find_by(store_variant_id: params[:store_variant_id])
    @product = Product.find(params[:product_id])
    respond_to do |format|
      if @shop_product.update_attributes!(product_id: params[:product_id], sync: params[:sync])
        format.html { redirect_to @shop_product, notice: 'Shop product was successfully updated.' }
        format.json { render :show, status: :ok, location: @shop_product }
      else
        format.html { render :edit }
        format.json { render json: @shop_product.errors, status: :unprocessable_entity }
      end
    end
  end

该表单来自单独的控制器,因此不是直接来自edit/:id。该记录是从循环/

的前端识别的
<% @in_store_variants.each do |variant| %>
    <% if @shop_products.find_by(store_variant_id: variant.id)  %>
      <% shop_product = @shop_products.find_by(store_variant_id: variant.id)  %>
    <% end %>
<%= form_for shop_product do |f| %>
   <%= f.collection_select :product_id, @products, :id, :sku %>
   <%= f.hidden_field :store_product_id, value: variant.product_id %>
   <%= f.hidden_field :store_variant_id, value: variant.id %>
   <%= f.hidden_field :shop_id, value: @shop.id %>
   <%= f.hidden_field :sync, value: true %>
   <%= f.submit "Sync" %>
<% end %>
.....
<% end %>

问题:

当显然从表单传递product_id时为什么不传递给控制器​​控制器中的update方法?

1 个答案:

答案 0 :(得分:1)

您的product_id位于params哈希中,但是您必须像这样访问它: params["shop_product"]["product_id"],因为它嵌套在shop_product下。 form_for将所有表单输入嵌套在关键字"shop_product"下的params哈希中。

在旁注中,我建议您使用强参数,而不要将参数中的值直接传递到更新方法中:)