Search code examples
ruby-on-railsmodelmodel-associations

Rails model joined has_many


Here is what I'm trying to do:

class Cashflow < ActiveRecord::Base
    belongs_to from_account, :class_name => 'Account'
    belongs_to to_account, :class_name => 'Account'
end

class Account < ActiveRecord::Base
    has_many :cashflows
end

where Account::cashflows is obviously a list of all cashflows that either have the account_id stored in from_account or in to_account.

I'm confused. What is the proper way of handling such a case? How bad design is this? What would be the proper way of designing such a relation?


Solution

  • I think you have the right structure as there can only two accounts be involved in a particular transaction/cashflow. if you use many to many association you would need to handle the validation for not involving more or less than 2 accounts. For your current structure you can change your moidel associations to be:

    class Cashflow < ActiveRecord::Base
      belongs_to from_account, :class_name => 'Account', :foreign_key => :from_account
      belongs_to to_account, :class_name => 'Account', :foreign_key => :to_account
    end
    
    class Account < ActiveRecord::Base
      has_many :debits, :class_name => 'Cashflow', :foreign_key => :from_account
      has_many :credits, :class_name => 'Cashflow', :foreign_key => :to_account
    
      def cashflows
        transactions = []
        transactions << self.debits
        transactions << self.credits
        transactions.flatten!
    
        ## or may be the following commented way
        # Cashflow.where('from_account = ? OR to_account = ?', self.id, self.id)
      end
    end
    

    This way you can keep track of the amount debited/credited in a particular account and also get the accounts involved in a particular transaction/cashflow.