6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsでSTIを使った場合のincludes

Last updated at Posted at 2015-08-10

STIを使うとincludesで困る場合がある。
たとえば以下のようなコード。

class User < ActiveRecord::Base
end

class Student < User
  has_one  :student_detail
end

class Staff < User
  has_one  :staff_detail
end

この場合、全ユーザーを取得するときにUser.all.includes(:student_detail, :staff_detail)とは書けない。Userにはそのようなアソシエーションは定義してないので。

以下のようにする。

users = User.all
users.group_by(&:class).each do |klass, records|
  associations = {
    Staff => [:staff_detail],
    Student => [:student_detail]
  }.fetch(klass, [])
  
  ActiveRecord::Associations::Preloader.new.preload(records, associations)
end

Rails 4.2.1で確認。
参考にしたページのActiveRecord::Associations::Preloaderの使い方ではうまくいかなかった。上記のpreloadメソッドもドキュメント化されてないようなので、また変わるかも。

参考にしたページ

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?