Same as #5235 but for InverseOf.
with_options inverse_of: :user do
has_many :portfolio_items, through: :portfolios
end
has_many :portfolio_items, through: :portfolios, inverse_of: :user
=>
app/models/user.rb:11:5: C: Rails/InverseOf: Specify an :inverse_of option.
has_many :portfolio_items, through: :portfolios
^^^^^^^^
I'm reading this and it says:
There are a few limitations to :inverse_of support:
- They do not work with :through associations.
- They do not work with :polymorphic associations.
- They do not work with :as associations.
So why do rubocop tell me to add inverse_of on has_many ... through: ... association ? 馃
Same issue as https://github.com/bbatsov/rubocop/issues/4751 . A fix was made here : https://github.com/bbatsov/rubocop/commit/0ec9f6e646a64d34138dd58b28cc6023bf356818
So we could add a similar check for :inverse_of
I tried verifying some patterns, but it seems that :inverse_of works with :as associations correctly.
class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
end
class Employee < ApplicationRecord
has_many :pictures, as: :imageable, inverse_of: :imageable
end
class Product < ApplicationRecord
has_many :pictures, as: :imageable
end
irb(main):001:0> employee = Employee.first
irb(main):002:0> picture = employee.pictures.build
irb(main):003:0> employee.equal? picture.imageable
=> true
However, it does not seem to work with :through or :polymorphic. I'm planning to fix this.
@delphaber AFAICS the documentation is wrong, I have a PR out to fix it: https://github.com/rails/rails/pull/31446
Worth noting that inverse_of is automatically inferred from as in Rails 5.2 so this can be relaxed a bit for >= 5.2. https://github.com/rails/rails/pull/28808
That was already taken care of in the original implementation of the cop - if it doesn't work it's a bug.
Most helpful comment
I'm reading this and it says:
So why do rubocop tell me to add
inverse_ofonhas_many ... through: ...association ? 馃