我有一个相当正常的类结构,使用多态关联:
class Contact < ActiveRecord::Base
has_many :opportunities, :as => :has_opportunities, dependent: :destroy
end
class Company < ActiveRecord::Base
has_many :opportunities, :as => :has_opportunities, dependent: :destroy
end
class Opportunity < ActiveRecord::Base
belongs_to :has_opportunities, polymorphic: true
belongs_to :contact, foreign_key: 'has_opportunities_id', conditions: "opportunities.has_opportunities_type = 'Contact'"
belongs_to :company, foreign_key: 'has_opportunities_id', conditions: "opportunities.has_opportunities_type = 'Company'"
end
在 Rails 4 中使用 :conditions 已被弃用,但我无法弄清楚允许从子对象访问父对象所需的“新”语法。
编辑:是的,你可以做机会.has_opportunities 它将返回你一个联系人或公司,但在代码中使用机会.联系人或机会.公司通常“更好”