ruby-on-rails – 在已毁坏的嵌套模型栏中的validates_uniqueness_of

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在已毁坏的嵌套模型栏中的validates_uniqueness_of前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个Project模型可以接受Task的嵌套属性.
class Project < ActiveRecord::Base  
  has_many :tasks

  accepts_nested_attributes_for :tasks,:allow_destroy => :true

end

class Task < ActiveRecord::Base  
validates_uniqueness_of :name end

任务模型中的唯一性验证在更新项目时有问题.

在编辑项目时,我删除一个任务T1,然后添加一个同名T1的新任务,唯一性验证限制了项目的保存.

params哈希看起来像

task_attributes => { {"id" =>
"1","name" => "T1","_destroy" =>
"1"},{"name" => "T1"}}

任务验证在销毁旧任务之前完成.因此验证失败.任何想法如何验证,以至于不考虑任务被销毁?

解决方法

安德鲁·法国在这个 thread年创建了一个补丁,其中的验证是在内存中完成的.
class Author
  has_many :books

  # Could easily be made a validation-style class method of course
  validate :validate_unique_books

  def validate_unique_books
    validate_uniqueness_of_in_memory(
      books,[:title,:isbn],'Duplicate book.')
  end
end

module ActiveRecord
  class Base
    # Validate that the the objects in +collection+ are unique
    # when compared against all their non-blank +attrs+. If not
    # add +message+ to the base errors.
    def validate_uniqueness_of_in_memory(collection,attrs,message)
      hashes = collection.inject({}) do |hash,record|
        key = attrs.map {|a| record.send(a).to_s }.join
        if key.blank? || record.marked_for_destruction?
          key = record.object_id
        end
        hash[key] = record unless hash[key]
        hash
      end
      if collection.length > hashes.length
        self.errors.add_to_base(message)
      end
    end
  end
end
原文链接:https://www.f2er.com/ruby/273244.html

猜你在找的Ruby相关文章