I have one model which has a polymorphic association with three other tables:
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
As you can see, the last 3 models belong to a "school" model and therefore have a column named school_id
. I want to retrieve all rows from user
such that their corresponding authenticatable school_id is equal to some value. To clarify, I'd like to do something like this:
User.joins(:authenticatable).where(:school_id => some_value)
As it is, that will result in an
ActiveRecord::EagerLoadPolymorphicError
on a final note, i managed to look up some documentation which suggests that using include on a polymorphic association should work, such as:
User.find(:all, :include => :authenticatable) (This works)
However if I do this:
User.find(:all, :include => :authenticatable).where(:school_id => some_value)
It breaks rails, because User.find(...)
returns an Array
and the where method is not defined for that class.
I've tried some other options and have not found a way to accomplish what I want. Can you help me? Thanks!