はじめに
双方向関連付けと inverse_of
が必要なケースについての学習記録です。
双方向関連付けとは
- Railsでは、基本的にモデル間の関連付けを双方向で設定する
- Active Recordは規約通りの関連付け名がある場合、二つのモデルが双方向に関連していることを自動で認識する
class User < ApplicationRecord
has_many :comments
end
class Comment < ApplicationRecord
belongs_to :user
end
双方向関連付けが自動で認識されなくなるケース
-
:foreign_key
:through
などのオプションが使われると、規約通りの関連付け名でないため自動で認識されなくなる
class User < ApplicationRecord
has_many :comments
end
class Comment < ApplicationRecord
belongs_to :user, class_name: "Author", foreign_key: "author_id"
end
# Railsの規約では相手モデルを指す外部キーのカラム名は `[モデル名]_id`が使われる
# :foreign_keyオプションを使うと、外部キーのカラム名を直接指定できる
inverse_of
で双方向関連付けを明示的に宣言する
class User < ApplicationRecord
- has_many :comments
+ has_many :comments, inverse_of: "user"
end
おわりに
複数モデルの同時保存する際のエラー解決策として inverse_of
に行き当たりました。同時保存時に外部キーがない事によるid違反を解消してくれるそうです。オプションを使用している際などは inverse_of
を書き忘れないように気を付けたいです。
参考