Rails 5:Update属性有多个通过连接表

时间:2017-10-08 16:40:52

标签: ruby-on-rails database ruby-on-rails-5 nested-forms has-many-through

我目前正在网上工作,而且我正在使用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)

1 个答案:

答案 0 :(得分:1)

你正在做has_many :though。在这种情况下,连接表需要有一个主键(通常为:id)。否则,您无法像此处一样直接访问连接表。

另一方面,如果您不需要直接访问连接表(例如,那里没有额外的列),那么您可以设置has_and_belongs_to_many,连接表没有id列。