Rails STI:强制超类将关联委托给子类

时间:2016-04-26 21:44:37

标签: ruby-on-rails inheritance activerecord

这是我到目前为止的STI设置:

class PhoneCall < ActiveRecord::Base
  belongs_to :from_phone_number, class_name: "PhoneNumber"
  belongs_to :to_phone_number, class_name: "PhoneNumber"
end

class OutgoingPhoneCall < PhoneCall
  has_one :user, through: :from_phone_number
end

class IncomingPhoneCall < PhoneCall
  has_one :user, through: :to_phone_number
end

根据其方向,您会看到Userfrom结尾处的to

在某些情况下这很好用:

OutgoingPhoneCall.joins(:user).where(user: { id: 2 })

......让我得到我想要的东西。

但是,我无法对超类进行相同的调用

PhoneCall.joins(:user).where(user: {id: 2}).count
ActiveRecord::ConfigurationError: Association named 'user' was not found on PhoneCall; perhaps you misspelled it?
from /Users/xxxx/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/activerecord-4.2.0/lib/active_record/associations/join_dependency.rb:218:in `find_reflection'

我想要一个干净的方式来获得User的电话,而无需再查询两次。

如何轻推我的超类PhoneCall以将此关联委托给其子类?

或者,或者,有没有办法让.joins在查询时使用子类?

1 个答案:

答案 0 :(得分:0)

您可以像这样编写查询:

PhoneCall.joins(from_phone_number: :user, to_phone_number: :user).where(users: {id: 2})