multiple belongs_to relationships between two classes in Rails

淺唱寂寞╮ 提交于 2019-11-30 15:32:32

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/7410641/multiple-belongs-to-relationships-between-two-classes-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!