0
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
4

1 回答 1

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)
于 2013-07-29T05:45:13.513 回答