好的,我以为我的答案非常好...... how to add records to has_many :through association in rails。但显然不是。
型号代码:
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
我基本上试图将库存与交易相匹配(有东西的人,有想要那些东西的人)
以下是我想要实现的目标:
itemlist_id
,以及他们想要的值quantity
的值= itemlist_id
。我们假设用户想要9个中的两个,看起来像这样:{ 9 => 2}
itemlist_id
,我将查看Inventories table
内部并提取inventory_ids
与itemlist_id
匹配的内容用户正在寻找并且inventory_id
的所有者不是他或她自己的用户。让我们说Inventories table
中有3个ID可以实现此目的:[X, Y, Z]
现在我要做的是创建Transactions
并将Transactions
和Inventories
相互关联。这一步的结果是双重的(我认为从视图的外观来看,它更容易编写:
inventory_id
的所有者应该看到他们的项目有2个transactions
(因此他们可以选择他们想要尊重的那个)transactions
中的每一个都有通知给每个X,Y和Z的所有者创建关联的代码
# 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
行,我收到错误:uninitialized constant Transaction::Transactory
更新
现在我遇到错误You tried to define an association named transaction on the model TransactionInventory, but this will conflict with a method transaction already defined by Active Record. Please choose a different association name.
我尝试指定class_names
和foreign_keys
,请参阅下面的示例:
belongs_to :transaction, foreign_key: "transaction_id", class_name: "Transaction"
答案 0 :(得分:1)
也许是一个加载问题,有可能在生产中没有任何修改的代码会因为急切加载而起作用。无论如何你可以尝试这个来解决你的问题:
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
根据我的建议为class_name
中的每一个has_many
指定class_name
有点过分,但其安全&#34;。
也许在您确认该解决方案有效后,您应该可以从has_many
的大部分内容中删除Transaction.transactories
,并仅保留{{1}}关系
答案 1 :(得分:1)
你在
中做错了transaction.inventories.create matched_inventory_id
顺便说一下它应该是matched_inventory_ids
,因为ids
方法总是返回一个数组
others.create
方法不接受id或id的数组。在这种情况下,它将接受库存的属性
要按ID进行关联,请使用other_ids
方法
transaction.inventory_ids = transaction.inventory_ids + matched_inventory_ids