2
0

More than 3 years have passed since last update.

ActiveRecord inverse_ofの使い所

Posted at

Rubocopの違反(RuboCop::Cop::Rails::InverseOf)が発生したので、inverse_ofについて調べてみました。

普通の関連付けではinverse_ofを使用しなくても、自動的に追えるようになっているので特に設定は必要ありません。

model.rb
class Parent < ApplicationRecord
  has_many :children
end

class Child < ApplicationRecord
  belongs_to :parent
end

しかし、関連付けでscopeをつける場合はinverse_ofを使用しなければいけません。以下のようにinverse_ofを設定してあげると逆関連づけを指定できます。

model.rb
class Parent < ApplicationRecord
  has_many :children -> { order(:height) }, inverse_of: :parent
end

class Child < ApplicationRecord
  belongs_to :parent, inverse_of: :children
end

参考にした記事のurl

Railsガイド inverse_of
https://railsguides.jp/association_basics.html#belongs-to%E3%81%AE%E3%82%AA%E3%83%97%E3%82%B7%E3%83%A7%E3%83%B3-inverse-of

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