【发布时间】:2011-11-02 00:10:17
【问题描述】:
我有一个模型与其他三个表具有多态关联:
class User < ActiveRecord::Base
belongs_to :authenticatable, :polymorphic => true
# == Schema Information
#
# Table name: employees
#
# id :integer(4) not null, primary key
# ...
# school_id :integer(4)
class Guardian < ActiveRecord::Base
has_one :user, :as => :authenticatable
belongs_to :school
# == Schema Information
#
# Table name: guardians
#
# id :integer(4) not null, primary key
# ...
# school_id :integer(4)
class Guardian < ActiveRecord::Base
has_one :user, :as => :authenticatable
belongs_to :school
# == Schema Information
#
# Table name: students
#
# id :integer(4) not null, primary key
# ...
# school_id :integer(4)
class Student < ActiveRecord::Base
has_one :user, :as => :authenticatable
belongs_to :school
如您所见,最后 3 个模型属于“学校”模型,因此有一个名为 school_id 的列。我想从user 中检索所有行,以便它们对应的可验证school_id 等于某个值。为了澄清,我想做这样的事情:
User.joins(:authenticatable).where(:school_id => some_value)
事实上,这将导致
ActiveRecord::EagerLoadPolymorphicError
最后,我设法查找了一些文档,这些文档表明在多态关联上使用 include 应该可以工作,例如:
User.find(:all, :include => :authenticatable) (This works)
但是,如果我这样做:
User.find(:all, :include => :authenticatable).where(:school_id => some_value)
它打破了轨道,因为 User.find(...) 返回一个 Array 并且没有为该类定义 where 方法。
我尝试了其他一些选项,但没有找到实现我想要的方法。你能帮助我吗?谢谢!
【问题讨论】:
标签: ruby-on-rails ruby activerecord join polymorphic-associations