具有多个潜在外键的同一表中的多个关联

时间:2011-02-09 18:12:38

标签: ruby-on-rails activerecord

我想做一些看似简单的联想:

class OrderWizard < ActiveRecord::Base
  belongs_to :buyer_wizard,     :class_name => MiniWizard.name
  belongs_to :seller_wizard,    :class_name => MiniWizard.name
end

class MiniWizard < ActiveRecord::Base
   has_one :order_wizard, :foreign_key = '????' # Could be buyer_wizard_id or seller_wizard_id

   def is_buyer_wizard?
     ??
   end

   def is_seller_wizard?
     ??
   end
end
  1. 相关的MiniWizard需要知道谁正在连接它。假设has_many:通过最好的方式去?如果是这样,模型将如何看待?

  2. MiniWizard实例需要知道它是买方还是卖方。坚持如何做到这一点。

1 个答案:

答案 0 :(得分:1)

你实际上可能想要两个关联,例如,这样的事情可能更准确地代表关系:

class MiniWizard < ActiveRecord::Base
   has_one :bought_order_wizard, :foreign_key => 'buyer_wizard_id', :class_name => 'MiniWizard'
   has_one :sold_order_wizard, :foreign_key => 'seller_wizard_id', :class_name => 'MiniWizard'

  def order_wizard
    bought_order_wizard || sold_order_wizard
  end

  def is_buyer_wizard?
    !bought_order_wizard.nil?
  end

  def is_seller_wizard?
    !sold_order_wizard.nil?
  end
end