There are three models:

class Image < ApplicationRecord has_many :lessons, as: :image end class Cover < ApplicationRecord has_many :lessons, as: :image end class Background < ApplicationRecord has_many :lessons, as: :image end 

Well, the model Lesson, respectively:

 class Lesson < ApplicationRecord belongs_to :image, polymorphic: true end 

As a result, I get an error:

Cannot eagerly load the polymorphic association: image

The error is caused by this code:

 Course.all.joins(groups: { lessons: :image }) 

What could be the problem?

  • at what point do you get an error? - Mikhail Vaysman
  • @MikhailVaysman added. - Colibri

1 answer 1

This is because the belongs_to :image, polymorphic: true association belongs_to :image, polymorphic: true polymorphic and may indicate generally any ActiveRecord models.

Therefore, to make a JOIN on it (hypothetically) in the general case, you need to attach it to a line of this type:

 INNER JOIN things ON lessons.image_id = things.id AND lessons.image_type = "Thing" 

... for each model (on the example of Thing ). And ORM'ke then rake in with a huge number of columns in the result set, choosing for each line what matched.

This is madness. And it is not implemented.


And you, most likely, are a fiasco in design and you need a Single Table Inheritance , the models of which are placed in one table and still succumb to JOIN 'y without incident.

A polymorph is better to use only when absolutely necessary.

  • Very interesting about the STI was to read. Thank you :) - Colibri
  • @ Can you give an example of "extreme necessity", please? So that I at least approximately knew about this "edge". - Colibri
  • @Colibri say, some generalized plugin for adding comments to any model. And even there, not in all situations polymorph will be appropriate. And in general, it does not fall on the relational model, the RDBMS cannot guarantee its consistency, so it’s easier to "avoid at all costs." - D-side