Rails 6.0升级至6.1后关联查询合并条件弃用警告问题
解决Rails 6.1中
type_documents关联的弃用警告 迁移到Rails 6.1后,调用type_documents关联时出现以下弃用警告:
ActionView::Template::Error (DEPRECATION WARNING: Merging ("documents"."type" IN ($1, $2, $3)) and (("documents"."type" = $1 OR "documents"."type" IN ($2, $3) AND "documents"."case_attachment_flag" = $4)) no longer maintain both conditions, and will be replaced by the latter in Rails 6.2. To migrate to Rails 6.2's behavior, use `relation.merge(other, rewhere: true)`.
原关联定义
has_many :type_documents, lambda { where(type: 'Document::Type') .or( where( type: ['Document::Some1', 'Document::Some2'], case_attachment_flag: true ) ) }, dependent: :destroy, as: :record, class_name: 'Document::Type'
问题原因
原关联中拆分的where和or条件导致Rails自动合并重复的type字段查询,触发了6.1版本的弃用警告。我们需要获取满足以下任一条件的文档:
type为Document::Typetype为Document::Some1/Document::Some2且case_attachment_flag为true
解决方案(无原生SQL)
使用Arel直接构建完整的条件逻辑,避免Rails拆分条件导致的合并问题:
has_many :type_documents, lambda { where( arel_table[:type].eq('Document::Type').or( arel_table[:type].in(['Document::Some1', 'Document::Some2']).and( arel_table[:case_attachment_flag].eq(true) ) ) ) }, dependent: :destroy, as: :record, class_name: 'Document::Type'
这种写法直接将整个查询条件定义为一个统一的OR结构,既符合需求,又不会触发弃用警告,同时兼容Rails 6.2的行为。
内容的提问来源于stack exchange,提问作者Goaul
相关产品推荐
相关产品推荐

