Rails 模型出现 rubocop 错误 - 指定 `:inverse_of` 选项

mr_*_*cle 4 ruby ruby-on-rails

我有两个具有可选关系的模型has_many- belongs_to,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

如您所见,关系基于非标准foregin_key名称(两个模型通过名为 的记录相互链接cms_journey_id)。添加后,foreign_key: 'cms_journey_id'我在两个模型中都遇到了 Rubocop 错误:

Rails/InverseOf: Specify an `:inverse_of` option
Run Code Online (Sandbox Code Playgroud)

rml*_*erd 10

如果您没有明确指定反向关系,Rails 会尽力使用类名作为猜测的基础来推断模型上的反向关联(至少对于has_manyhas_one和关联)。belongs_to

但每当您使用作用域或设置非标准命名时,您都需要明确告诉 Rails 如何使用inverse_of. 在你的情况下:

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
Run Code Online (Sandbox Code Playgroud)

为了供将来参考,Rubocop 关于个别警察的文档总体上是良好且清晰的,并且包括“好”和“坏”的示例。只需搜索警察姓名(例如“Rails/InverseOf”)即可。