Rails model with rubocop error - specify an `:inverse_of` option

Viewed 2934

I've got two models with optional relations has_many - belongs_to, like below:

class Journey < ApplicationRecord
  has_many :activities, dependent: :destroy, foreign_key: 'cms_journey_id'
end

class Activity < ApplicationRecord
  belongs_to :journey, optional: true, foreign_key: 'cms_journey_id'
end

As you see the relation is based on non-standard foregin_key name (both models are linked with each other by record called cms_journey_id). After I added foreign_key: 'cms_journey_id' I'm getting Rubocop error in both models:

Rails/InverseOf: Specify an `:inverse_of` option
1 Answers

If you don't explicitly specify the inverse relationships, Rails does its best to infer the inverse association on a model (at least for has_many, has_one, and belongs_to associations) using the class names as the basis for its guesses.

But anytime you use a scope or set non-standard naming, you need to explicitly tell Rails how to navigate the associations using inverse_of. In your case:

class Journey < ApplicationRecord
  has_many :activities, dependent: :destroy, 
                        foreign_key: 'cms_journey_id', 
                        inverse_of: :journey
end

class Activity < ApplicationRecord
  belongs_to :journey, optional: true, 
                       foreign_key: 'cms_journey_id', 
                       inverse_of: :activities
end

For future reference, the Rubocop documentation on individual cops is generally good and clear, and includes examples of 'good' and 'bad'. Just search for the cop name (e.g. 'Rails/InverseOf') and you're in good shape.

Related