Creating joined records using has_many :through

蓝咒 提交于 2019-12-06 14:50:49

Perhaps a loading issue, it is possible that in production your code without any modification would work because of eager loading. Anyhow you could try this to fix your issue:

class Transaction < ActiveRecord::Base
  belongs_to :request
  has_many :transactories, class_name: 'Transactories'
  has_many :inventories, through: :transactories
end

class Inventory < ActiveRecord::Base
  has_many :transactories, class_name: 'Transactories'
  has_many :transactions, through: :transactories
end

class Transactories < ActiveRecord::Base
  belongs_to :inventory, class_name: 'Inventory'
  belongs_to :transaction, class_name: 'Transaction'
end

It's a bit too much to specify class_name for each and every of your has_many like I suggest, but its "safe".

And perhaps after you confirm that solution works you should be able to remove class_name from most of your has_many and keep it only for Transaction.transactories relation

You are doing a wrong assignment in

transaction.inventories.create matched_inventory_id

And by the way it should be matched_inventory_ids because the ids method returns allways an array

The others.create method does not accept id or an id's array. It will accept attributes of the inventory in that case

To do association by id use the other_ids method

transaction.inventory_ids = transaction.inventory_ids + matched_inventory_ids 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!