我有两个具有可选关系的模型 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
如您所见,该关系基于非标准的 foregin_key
名称(两个模型通过名为 cms_journey_id
的记录相互链接)。添加 foreign_key: 'cms_journey_id'
后,我在两个模型中都遇到了 Rubocop 错误:
Rails/InverseOf: Specify an `:inverse_of` option
最佳答案
如果您没有明确指定反向关系,Rails 会尽力推断模型的反向关联(至少对于 has_many
、has_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
为了便于日后引用,Rubocop 关于个别警察的文档总体上是好的和清晰的,并且包括“好”和“坏”的示例。只需搜索 cop 名称(例如“Rails/InverseOf”)即可。
关于ruby-on-rails - 带有 rubocop 错误的 Rails 模型 - 指定 `:inverse_of` 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62885060/