[英]Rails STI: Force superclass to delegate associations to subclasses
Here's the STI setup I've got so far: 这是我到目前为止的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
You'll see that I expect a User
at the end of either a from
or to
depending on its direction. 您会看到,我希望一个User
位于from
或to
的末尾,具体取决于其方向。
This works fine in some cases: 在某些情况下,这可以正常工作:
OutgoingPhoneCall.joins(:user).where(user: { id: 2 })
...gets me exactly what I want. ...让我得到我想要的。
However, I cannot make the same call on the superclass 但是,我无法在超类上进行相同的调用
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'
I would like a clean way to get a User
's phone calls without having to query twice. 我想以一种干净的方式来获得User
的电话,而不必查询两次。
How can I nudge my superclass PhoneCall
to delegate this association to its subclasses? 如何轻推我的超类PhoneCall
将此关联委托给它的子类?
Or, alternately, is there a way to get .joins
to use the subclasses when querying? 或者,是否有一种方法可以让.joins
在查询时使用子类?
您可以这样编写查询:
PhoneCall.joins(from_phone_number: :user, to_phone_number: :user).where(users: {id: 2})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.