我目前工作的一個網上商店,我使用Rails 5.我有以下型號和關係:Rails的5:更新屬性中有很多通過連接表
# Products
class Product < ApplicationRecord
has_many :product_variants
has_many :variants, through: :product_variants
...
class Variant < ApplicationRecord
has_many :product_variants
has_many :products, through: :product_variants
...
# My join table between Product and Variant
class ProductVariant < ApplicationRecord
belongs_to :price, optional: true
belongs_to :product, optional: true
belongs_to :variant, optional: true
我ProductVariant
模型有附加屬性,我想更新,t.integer "quantity"
。當我在form_for
中更新這個屬性時,我有點失落。
我對形式的當前解決方案看起來是這樣的(我用的HAML):
= form_for @product, html: { method: :patch } do |product_builder|
= product_builder.fields_for :product_variants, product_variant do |variant_builder|
= variant_builder.hidden_field :variant_id, value: product_variant.variant.id
= variant_builder.number_field :quantity
= variant_builder.submit
但它不能正常工作。如果連接表有一個ID列,感覺會更容易,但我想這在數據庫中是多餘的。當我點擊提交按鈕時,它目前似乎創建了另一個ProductVariant
實例。
我應該怎樣才能正確更新我的連接表中的quantity
屬性?
完成
這是當我點擊提交記錄的內容:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"uisxjfvj9LxZVJWcDVos66tJWNfHkld5+/gdfGv1D2WZsrLJcH7KLxb5eSDAYIL23mEEho18Pv/53bSEP8cC9A==", "product"=>{"product_variants_attributes"=>{"0"=>{"variant_id"=>"1", "product_id"=>"11", "quantity"=>"20", "id"=>""}}}, "commit"=>"Update Product variant", "id"=>"11"} Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT ? [["id", 11], ["LIMIT", 1]] Unpermitted parameter: :id (0.1ms) begin transaction Brand Load (0.2ms) SELECT "brands".* FROM "brands" WHERE "brands"."id" = ? LIMIT ? [["id", 4], ["LIMIT", 1]] Variant Load (0.2ms) SELECT "variants".* FROM "variants" WHERE "variants"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]] Brand Exists (0.2ms) SELECT 1 AS one FROM "brands" WHERE "brands"."name" = ? AND ("brands"."id" != ?) LIMIT ? [["name", "Fredric Malle"], ["id", 4], ["LIMIT", 1]] SQL (0.4ms) INSERT INTO "product_variants" ("variant_id", "product_id", "quantity") VALUES (?, ?, ?) [["variant_id", 1], ["product_id", 11], ["quantity", 20]] (2.7ms) commit transaction (0.2ms) SELECT COUNT(*) FROM "note_parts" INNER JOIN "product_note_parts" ON "note_parts"."id" = "product_note_parts"."note_part_id" WHERE "product_note_parts"."product_id" = ? [["product_id", 11]] Redirected to http://localhost:3000/products/11/edit Completed 302 Found in 15ms (ActiveRecord: 4.0ms)
你正在接收'未經許可的參數::id',你有一個'id'屬性,你不是在強烈的參數。 –
謝謝@SebastiánPalma,是的,看到了。我真的不想發送一個ID,因爲它是一個連接表,ID列不存在。如果我添加id到我的強參數中,會出現以下錯誤:'NoMethodError(未定義的方法'to_sym'爲nil:NilClass):'。所以我覺得我有更大的問題。 :( – Anders