简体   繁体   中英

Array not saving from one model to another in rails

I am trying to save an array of multiple ids (item_variation_ids) to a model called items_stock from item variations model. In a column called item_variation_ids in item_stock, it is saving the ids like [1,2,3] for twice. I want the item_variation_ids to be saved once only with 1,2,3 in a single column. My item_variation model

#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

My item model

 #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

My item_stock model

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM