Eager load differently nested polymorphic

前端 未结 1 1528
无人共我
无人共我 2021-02-06 17:34

Using Rails 3.2. My models are nested in such a way:

  • Review => Reviewable (Country or Shop)
  • Country => CountryDay => Shop => Photos
  • Shop => Photo
相关标签:
1条回答
  • 2021-02-06 18:00

    I think I had the same problem just now. I got an ActiveRecord::EagerLoadPolymorphicError when trying to load associations. My solution was to put together a custom join statement which I've put into a scope for easier usage.

    Untested, but this may get you going:

    class Review < ActiveRecord::Base
      scope :eagerly_loaded, -> {
        joins('
          INNER JOIN shops 
          ON (reviews.reviewable_type = "Shop" AND reviews.reviewable_id = shops.id)
          INNER JOIN countries 
          ON (reviews.reviewable_type = "Country" reviews.reviewable_id = countries.id)
        ')
      }
    end
    

    You then use @user.reviews.eagerly_loaded. Make sure to use a matching .group()-statement to only get the ones you need.

    0 讨论(0)
提交回复
热议问题