7

I have a Transaction class. Each object of this class includes one issuing account, one sending account and one receiving account. Each of these is an instance of Account class. In my Transaction table, I have issuer_id, sender_id and receiver_id.

How should I specify relationship between Transaction and Account so that I can call

transaction.issuer
transaction.sender
transaction.receiver

Thank you.

user229044
  • 232,980
  • 40
  • 330
  • 338
AdamNYC
  • 19,887
  • 29
  • 98
  • 154

1 Answers1

16

Use :class_name to specify the class name, when it can't be guessed from the association name:

class Transaction
  belongs_to :issuer,   :class_name => 'Account'
  belongs_to :sender,   :class_name => 'Account'
  belongs_to :receiver, :class_name => 'Account'
end

class Account
  has_many :issued_transactions,   :foreign_key => :issuer,   :class_name => 'Transaction'
  has_many :sent_transactions,     :foreign_key => :sender,   :class_name => 'Transaction'
  has_many :received_transactions, :foreign_key => :receiver, :class_name => 'Transaction'
end

You can read more in the documentation.

Koen.
  • 25,449
  • 7
  • 83
  • 78
user229044
  • 232,980
  • 40
  • 330
  • 338
  • Thanks a lot meagar. I was puzzled by how I could specify the has_many/has_one in Account class vis-a-vis Transaction class. It turns out that I don't need to. – AdamNYC Sep 14 '11 at 02:47
  • Not unless you intend to reference an account's transactions. – user229044 Sep 14 '11 at 02:48
  • I was about to add that question. How should I call something like: acccount_one.transactions_as_issuer? – AdamNYC Sep 14 '11 at 02:50
  • See the updated `:foreign_key` stuff; I wasn't thinking when I said use `:inverse_of`. – user229044 Sep 14 '11 at 02:55
  • huhm, the has_many :foreign_key :classname specification doesn't seem to work for me. (I changed foreign_keys to :issuer_id etc. but it doesn't work either) – AdamNYC Sep 14 '11 at 03:09
  • It is `:class_name`, not `:classname` – user229044 Sep 14 '11 at 03:10
  • 1
    Thanks a bunch. In terms of user experience, SO can't be better than this :) What I learn from this is that belongs_to and has_one/many can be defined independently. Foreign keys must be stated explicitly when having multiple "roles". – AdamNYC Sep 14 '11 at 03:23
  • Is this possible to do ```has_many :transactions``` and print out an aggregated list? – James Apr 10 '14 at 20:22