我正在将一个Rails 5.2应用程序升级到Rails 6,并且在我的多态模型中遇到了一个错误。它可以belong_to其他几个模型,但它本身只需要一个身体。
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当我创建或编辑一个注释,即使它有一个主体和用户和值得注意的设置正确,验证失败,因为它说专业和主题不能是空白的。
=> #,@messages={:topic=>“必须存在”,:profession=>“必须存在”},@details={:topic=>{:error=>:blank},:profession=>{:error=>:blank}}>
如果我在上面的模型中注释掉了belongs_to,它就会验证得很好。
我搜索了这些文档,看看是否可以在任何地方解释这种行为,但是验证或升级指南中的任何内容似乎都不能解决多态关联方面的问题。
发布于 2020-11-27 20:54:31
现在您需要将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
https://stackoverflow.com/questions/65043612
复制相似问题