Kalanamith
Kalanamith

Reputation: 20688

How to persist data via has_many through association in rails

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

This is my model and I want to save data in to Batch, TransactionGroup and transaction

How to perform this task?

 batch.transaction_groups.transactions.build(:transaction_group_id => batch.transaction_groups.id) #this gaves me an error

Upvotes: 0

Views: 243

Answers (1)

Aman Garg
Aman Garg

Reputation: 4218

First you will have to find transaction_group record which you want to associate with transaction:

transaction_group = batch.transaction_groups.find(id) #(or batch.transaction_groups.first for first record)

Then you can create associated transaction record by:

transaction_group.transactions.build

or,

batch.transactions.build(:transaction_group_id => transaction_group.id)

Upvotes: 1

Related Questions