【问题标题】:Configuration to allow optional belongs_to association not working in rail 6允许可选的 belongs_to 关联的配置在 rail 6 中不起作用
【发布时间】:2019-12-09 21:12:08
【问题描述】:

在 rails 5 中,我可以使用此设置将 belongs_to 关联设为可选:

Rails.application.config.active_record.belongs_to_required_by_default = false

但这似乎在 Rails 6 中不起作用。有没有办法在 Rails 6 中做到这一点?

【问题讨论】:

    标签: ruby-on-rails-6


    【解决方案1】:

    查看 Rails 5 的新框架默认文件,它有以下内容

    # config/initializers/new_framework_defaults.rb
    # Require `belongs_to` associations by default. Previous versions had false.
    Rails.application.config.active_record.belongs_to_required_by_default = true
    

    看来Rails 6 的选项已被完全删除。因此,您需要根据具体情况添加optional: true。就我而言,在大多数情况下,我结束了重写代码以便需要关联。

    【讨论】:

    • 该选项在 rails 6.1.4 中仍然适用于我
    【解决方案2】:

    该选项在 Rails 6 中仍然有效,但您需要确保在加载默认配置值后设置它,即 config.load_defaults 6.0

    最好的地方是config/application.rb的尽头

        ...
        # Don't check for the existence of belongs_to records
        config.active_record.belongs_to_required_by_default = false
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多