Rails 6 个多态模型给出验证错误

Rails 6 polymorphic model giving validation errors

我正在将 Rail 5.2 应用程序升级到 Rails 6,并且 运行 我的一个多态模型出现错误。它可以 belong_to 几个其他模型,但它本身只需要一个 body.

class Note < ApplicationRecord
  belongs_to :notable, polymorphic: true
  belongs_to :user

  belongs_to :profession
  belongs_to :topic

  has_many :notes, as: :notable, :dependent => :destroy
  validates :body, presence: true, allow_blank: false
end

当我创建或编辑笔记时,即使 body 和用户和名人设置正确,验证也会失败,因为它说职业和主题不能为空。

=> #<ActiveModel::Errors:0x00005622cd43ed10 @base=#<Note id: 768, notable_type: "Topic", notable_id: 4735, user_id: 8050, body: "foo", created_at: "2020-07-22 21:55:41", updated_at: "2020-07-22 21:55:41", communal: true, is_card: false, title: "test">, @messages={:topic=>["must exist"], :profession=>["must exist"]}, @details={:topic=>[{:error=>:blank}], :profession=>[{:error=>:blank}]}>

如果我在上面的模型中注释掉 belongs_to,它可以正常验证。

我搜索了文档,看看是否可以在任何地方解释该行为,但验证或升级指南中似乎没有任何内容可以处理围绕多态关联的问题。

您现在需要将 optional: true 添加到 belongs_to 或 rails 默认情况下添加验证。见下文:

class Note < ApplicationRecord
  belongs_to :notable, polymorphic: true
  belongs_to :user

  belongs_to :profession, optional: true
  belongs_to :topic, optional: true

  has_many :notes, as: :notable, :dependent => :destroy
  validates :body, presence: true, allow_blank: false
end

相关文档在此处:https://edgeguides.rubyonrails.org/upgrading_ruby_on_rails.html#new-framework-defaults