LoginSignup
57
47

More than 5 years have passed since last update.

Rails4で中間テーブルがポリモーフィックなテーブルとhas_many throughする

Posted at

問題

中間テーブルを簡単につなぐことができるhas_many throughは便利だけど、中間テーブルがポリモーフィックな場合はどう書けばいいの?

こう書けば良い

以下の図のように、StudyPaticipantが中間テーブルかつポリモーフィックなモデルだとします。

  User - has_many -> StudyParticipant - has_many -> Subsciption
                                      - has_many -> Adoption

で、こんな感じにSubscriptionやAdoptionを引っ張りたい。

user.subscriptions
user.adoptions

そんなときはこんな感じに定義すれば良いようです。

# user.rb
class User < ActiveRecord::Base
  has_many :study_participants
  has_many :subscriptions, through: :study_participants, source: :study, source_type: 'Subscription'
  has_many :adoptions, through: :study_participants, source: :study, source_type: 'Adoption'
end

# study_participant.rb
class StudyParticipant < ActiveRecord::Base
  belongs_to :study, polymorphic: true
end

# subscription.rb
class Subscription < ActiveRecord::Base
  has_many :study_participants, as: :study
end

# adoption.rb
class Adoption < ActiveRecord::Base
  has_many :study_participants, as: :study
end

Rails3のときはhas_manyのconditionsキーでベタに書いていた気がするのですが、Rails4からはsource_typeというキーが用意されていました。

57
47
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
57
47