0

我目前工作的一个网上商店,我使用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)

+0

你正在接收'未经许可的参数::id',你有一个'id'属性,你不是在强烈的参数。 –

+0

谢谢@SebastiánPalma,是的,看到了。我真的不想发送一个ID,因为它是一个连接表,ID列不存在。如果我添加id到我的强参数中,会出现以下错误:'NoMethodError(未定义的方法'to_sym'为nil:NilClass):'。所以我觉得我有更大的问题。 :( – Anders

回答

1

你做一个has_many :though。在这种情况下,连接表需要有一个主键(通常是:id)。否则,你不能像这里所要的那样直接访问连接表。另一方面,如果不需要直接访问连接表(例如,不存在额外的列),那么可以设置has_and_belongs_to_many,连接表没有id列。

+0

谢谢,我添加了表的主键,现在它的工作。 – Anders

相关问题