class Batch < ActiveRecord::Base
has_many :transaction_groups
has_many :transactions , :through=>:transaction_groups
end
class TransactionGroup < ActiveRecord::Base
attr_accessible :g_id
belongs_to :batch
has_many :transactions, dependent => :destroy
end
class Transaction < ActiveRecord::Base
attr_accessible :reference, :transaction_group_id
belongs_to :transaction_group
end
这是我的模型,我想将数据保存到Batch,TransactionGroup和transaction
如何执行此任务?
batch.transaction_groups.transactions.build(:transaction_group_id => batch.transaction_groups.id) #this gaves me an error
答案 0 :(得分:1)
首先,您必须找到要与事务关联的transaction_group记录:
transaction_group = batch.transaction_groups.find(id) #(or batch.transaction_groups.first for first record)
然后您可以通过以下方式创建关联的交易记录:
transaction_group.transactions.build
,或者
batch.transactions.build(:transaction_group_id => transaction_group.id)