简体   繁体   English

如何通过Rails中的关联通过has_many持久化数据

[英]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 这是我的模型,我想将数据保存到Batch,TransactionGroup和Transactions

How to perform this task? 如何执行此任务?

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

First you will have to find transaction_group record which you want to associate with transaction: 首先,您必须找到要与事务关联的transaction_group记录:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM