这是我到目前为止的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
根据其方向,您会看到User
或from
结尾处的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
在查询时使用子类?
答案 0 :(得分:0)
您可以像这样编写查询:
PhoneCall.joins(from_phone_number: :user, to_phone_number: :user).where(users: {id: 2})