Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving rows from one table with polymorphic associations

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!

like image 600
sauronnikko Avatar asked Mar 19 '26 05:03

sauronnikko


1 Answers

You can try to solve it by using SQL query in joins statement:

Model1.joins("INNER JOIN model2 ON model2.id = model1.polymorphizm_id INNER JOIN model3 ON model3.id = model1.polymorphizm_id INNER JOIN model4 ON model4.id = model1.polymorphizm_id").where("model2.column_id = ... or model3.column_id = ... or model4.column_id = ...")

I not actually try it, but polimorphic assoc. adds 2 columns to model: xxx_type and xxx_id. They serve to handle assoc. with multiple models.

like image 166
bor1s Avatar answered Mar 21 '26 20:03

bor1s