rails 中的数组未从一个模型保存到另一个模型

Array not saving from one model to another in rails

我正在尝试将多个 ID (item_variation_ids) 的数组保存到项目变体模型中名为 items_stock 的模型中。在 item_stock 中名为 item_variation_ids 的列中,它保存了两次像 [1,2,3] 这样的 ID。我希望 item_variation_ids 在单个列中仅使用 1,2,3 保存一次。 我的 item_variation 模特

#app/models/item_variation
class ItemVariation < ApplicationRecord
  belongs_to :item
  validates_associated :item
  after_save :add_to_item_stock

 def add_to_item_stock
   ItemStock.create(item_variation_ids: ItemVariation.ids, items_id: items_id)
 end
end

我的物品模型

 #app/models/item
 class Item < ApplicationRecord
  has_many :item_variations, foreign_key: :items_id
  has_many :item_stocks, foreign_key: :items_id
  accepts_nested_attributes_for :item_stocks
end

我的item_stock模特

#app/models/item_stock
class ItemStock < ApplicationRecord
  belongs_to :item
end

但是您如何知道哪些 ItemVariation id 应该放在 ItemStock 上?每次保存任何变体时,您都会创建一个 ItemStock。我什至不认为你需要设置那个 ids 数组,因为 ItemStock 已经属于一个有很多变化的项目(@item_stock.item.variations,你就完成了)。

现在您还在谈论一个您以前从未提到过的 stock_qty 属性,您从未在回调中设置它,也没有显示您的数据库架构。那笔钱从哪里来?是要加到当前 item_stock?

的变体属性

我也不明白为什么您显示的代码有很多商品库存。

我会做一个疯狂的猜测,并建议你做这样的事情:

ItemStock
  belongs_to :item
  belongs_to :item_variation
end

ItemVariation
  after_save :add_to_item_stock

  def add_to_item_stock
    item_stock = self.item.item_stock.where(item_variation_id: self.id).first_or_initialize
    item_stock.stock_qty = self.stock_qty
    item_stock.save
  end
end

但正如我所说,这是一个错误的猜测。我建议您首先尝试了解您在做什么,因为您似乎只是从您链接的那个问题中复制代码,而您并没有真正理解它。