プログラミングガール

Developing a better me

Rails|ポリモーフィックで子から親へのeager loadを行う

困ったこと

↓以下のような関連を持つクラスに対し、子から親に対して関連を eager load で取得しようとしたところ、
Cannot eagerly load the polymorphic association :reviewableというエラーをくらった。

class User < ActiveRecord::Base
  has_many :reviews
end

class Review < ActiveRecord::Base
  belongs_to :user
  belongs_to :reviewable, polymorphic: true
end

class Shop < ActiveRecord::Base
  has_many :reviews, as: :reviewable
end
@reviews = Review.includes(:reviewable).references(:reviewable)

どうやらincludesでの関連付けはだめらしい。

解決策

This error is raised when trying to eager load a polymorphic association using a JOIN. Eager loading polymorphic associations is only possible with ActiveRecord::Relation#preload. ActiveRecord::EagerLoadPolymorphicError

ばっちり書いてあった。笑
JOINを用いての eager load はだめらしい。 preloadを使いましょうね。