阵列未从一个模型保存到导轨中的另一个模型

时间:2018-12-01 11:21:39

标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5 rails-activerecord

我正在尝试将多个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

1 个答案:

答案 0 :(得分:1)

But how do you know which ItemVariation ids should go on that ItemStock? and you are creating one ItemStock each time any variation gets saved. I don't even think you need to set that ids array since the ItemStock already belongs to an Item which has many variations (@item_stock.item.variations and you are done).

Also now you are talking about a stock_qty attribute you never mentioned before, you are never setting it on the callback and you didn't show your database schema. where does that amout come from? is an attribute on the variation that you want to sum to the current item_stock?

I also don't understand why an item has many item stocks for the code you are showing.

I'll do a wild guess and suggest you do something like:

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

but as I said, it's a wiiiiild guess. I'd recommend you to first try to understand what you are doing, because it seems like you just copied to code from that question you linked and you are no actually understanding it.