LoginSignup
3
0

More than 3 years have passed since last update.

【Rails】一対一対多のアソシエーション

Last updated at Posted at 2020-04-02

結局は基本的なことなのですが、少し変わると途端にハマってしまう。
アソシエーションがうまくいかずに時間を溶かしてしまったので、そんな過去の自分といるかもしれない未来の誰かのために書き残しておきます。

テーブル構造

UserモデルとTagモデルの中間テーブルから派生させたTagSettingモデルを作りました。
erd.jpg
ただ、今回の話にはUserモデルはあまり関係ありません。
また、この後「tag_usersとtag_settingsを別々にしなくていいんじゃないか?」という指摘を受けてテーブル構造を変えました。なので、例としては少々不適切かもしれませんがご容赦を。

モデルのアソシエーション

user.rb
class User < ApplicationRecord
  has_many :tag_users
  has_many :tags, through: :tag_users
  has_many :tag_settings
end
tag_user.rb
class TagUser < ApplicationRecord
  belongs_to :user
  belongs_to :tag
  belongs_to :tag_setting
end
tag_setting.rb
class TagSetting < ApplicationRecord
  has_one :tag_user
  has_one :tag, through: :tag_user
  belongs_to :user
end
tag.rb
class Tag < ApplicationRecord
  has_many :tag_users
  has_many :tag_settings, through: :tag_users
end

注意点

中間テーブルへのアソシエーションを追加する

has_many :tag_usersなしでhas_many :tag_settings, through: :tag_usersを定義することはできない。
また、中間テーブルへのアソシエーションの方を上に記述する必要がある。

単数形・複数形に注意する

has_many :tag_settings, through: :tag_users
has_manyのときは:throughも複数形

has_one :tag, through: :tag_user
has_oneのときは:throughも単数形

リンク

3
0
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
3
0