Reputation: 1481
When i submit my form, I have the following:
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):
Method:
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
The form is coming from a separate controller so it's not coming directly from edit/:id
. The record is identified on the front-end from a loop/
<% @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 %>
Question:
Why is the product_id
not being passed to the update method in the controler controller when it's clearly being passed on from the form?
Upvotes: 0
Views: 31
Reputation: 2715
Your product_id is in the params hash, but you have to access it like so:
params["shop_product"]["product_id"]
because it is nested under shop_product. The form_for is nesting all the form inputs in the params hash under the key "shop_product"
.
On a side note I would recommend you to work with strong params instead of passing the values from the params directly into your update method :)
Upvotes: 1