dev/mom0tomo

技術メモ

Railsのアソシエーションの仕組み

理解するのにものすごく時間がかかったので、まとめておく。

アソシエーションとは

簡単にいうとモデルを参照するためのメソッド。
例は下記に示す。

メソッドはふだん使うときに書くが(当たり前)、アソシエーションは使い道も書き方も決まっていてるので、初めにまとめて書いておく決まり。

アソシエーションを利用するケース

usersとitemsという多対多のテーブルがあり、relationshipsという中間テーブルを使う場合を考える。

models/user.rb

class User < ApplicationRecord
  has_many :relationships
  has_many :items, through: :relationships
end

models/item.rb

class Item < ApplicationRecord
  has_many :relationships
  has_many :users, through: :relationships
end

models/like.rb

class Relationship < ApplicationRecord
  belongs_to :user
  belongs_to :item
end

下記のように使うことができるが、

@user = item.user

この理由は、 models/item.rb

has_many :users, through: :relationships

上記のアソシエーションはもともと以下のようなメソッドを省略したものだから。

def user
  User.find_by(id: Relationship.find(self.id).item_id)
end