我正在尝试创建Transaction
同时是Request
的孩子,也是Inventory
的多对多关系中的一部分。
型号代码:
class Transaction < ActiveRecord::Base
belongs_to :request
has_many :transactories
has_many :inventories, through: :transactories
end
class Inventory < ActiveRecord::Base
has_many :transactories
has_many :transactions, through: :transactories
end
class Transactory < ActiveRecord::Base
belongs_to :inventory
belongs_to :transaction
end
以下是我想要实现的流程:
现在我要做的是创建属于请求的交易(先前已创建请求)并将交易和库存相互关联。这一步的结果是双重的(我认为从视图的外观来看更容易编写:
创建关联的代码
# Assume overarching parent request has been created, called @requestrecord
# Step 1, @transactionparams = { 9 => 2 }
@transactionparams.each do |itemlist_id, quantity|
# Step 2 matched_inventory_id = [X,Y,Z]
matched_inventory_id = Inventory.where.not(signup_id: @requestrecord.signup.id).where(itemlist_id: itemlist_id).ids
# Step 3, 2 transactions created each with itemlist_id of 9, each associated with inventory_ids X, Y, Z. In turn, inventory_ids X, Y, Z each associated with each of the two transactions created
quantity.to_i.times do
transaction = @requestrecord.transactions.create(itemlist_id: itemlist_id)
transaction.inventories.create matched_inventory_id
end
end
我无法做到的路线是第3步:
transaction.inventories.create matched_inventory_id
这会抛出一个错误,即create的参数必须是哈希值。我也尝试过:
matched_inventory_id.each do |id|
transaction.inventories.create(inventory_id: id)
end
此操作失败,因为inventory_id不是有效属性。 所以...两个问题:
has_many :through
中的含义,只要我将Inventory
与Transactions
相关联,我就会自动将Transactions
与Inventories
相关联,对吗?答案 0 :(得分:0)
最后有人回答了这个问题:Creating joined records using has_many :through
基本上我首先创建属于Transaction
父级的Request
,然后将其与库存相关联,如下所示:
transaction.inventory_ids += matched_inventory_ids
这一新行取代了旧的代码行:
transaction.inventories.create matched_inventory_id
是的,一旦它与一种方式相关联,双向也起作用,因为它是一种多对多的关系。