Eager loading of polymorphic associations in ActiveRecord

后端 未结 3 765
日久生厌
日久生厌 2021-02-06 11:48

This is my first time using Rails and I was wondering if it\'s possible to load a has one polymorphic association in one SQL query? The models and associations between them are

3条回答
  •  情书的邮戳
    2021-02-06 12:27

    (This is for Rails 3 syntax.)

    MetaWhere is an awesome gem for making complex queries that are outside of ActiveRecord's usual domain easy and ruby-like. (@wayne: It supports outer joins as well.)

    https://github.com/ernie/meta_where

    Polymorphic joins are a little trickier. Here's how I did mine with MetaWhere:

    Image.joins(:asset.type(AssetModel)).includes(:asset)
    

    In fact, I made a convenience method in my polymorphic-association-having class:

      def self.join_to(type)
        joins(:asset.type(type)).includes(:asset)
      end
    

    So it will always query & eager load a particular type of asset. I haven't tried mixing it with multiple types of join in one query. Because polymorphism works using the same foreign key to reference different tables, on the SQL level you have to specify it as separate joins because one join only joins to one table.

    This only works with ActiveRecord 3 because you have access to the amazing power of AREL.

提交回复
热议问题