LoginSignup
5
4

More than 5 years have passed since last update.

Rails: Polymorphicな中間テーブルがある場合のアソシエーションの仕方

Posted at

自分用にメモ

User, Taggings, Tagというモデルがる。

UserはTaggingsをthrougして沢山のtagを持っている。

has_many :taggings, as: :taggable, dependent: :destroy
has_many :tags, through: :taggings

class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :taggable, polymorphic: true
end

class Tag < ActiveRecord::Base
has_many :taggings, dependent: :destroy
has_many :users, through: :taggings, source: :taggable, source_type: 'User'

validates :name, presence: true
end

5
4
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
5
4