如何通过rails中的关联通过has_many保存数据

时间:2013-07-29 05:16:26

标签: ruby-on-rails activerecord

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

1 个答案:

答案 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)