0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】双方向関連付けとinverse_of

Posted at

はじめに

双方向関連付けと 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 を書き忘れないように気を付けたいです。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?