ruby-on-rails - 带有 rubocop 错误的 Rails 模型 - 指定 `:inv

我有两个具有可选关系的模型 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_manyhas_onebelongs_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/

相关文章:

azure - 卡夫卡与 SignalR

java - 在 Java 中不使用类创建对象

azure-devops - 在 YAML 部署作业中部署后检查应用程序运行状况端点的最佳方法?

php - 如何在 WooCommerce 中获取产品特定的元数据

r - 为什么同一个查询使用 dplyr 在不同的 R session 上返回不同的结果?

python - 为什么我会收到 KeyError : 0

amazon-web-services - 我们可以在 Route 53 AWS DNS 服务中创建

css - 对齐元素 : center not working in flexbox

html - 在 flex 中将 div 的内容右对齐

python - 在 django urls.py 中访问请求对象