Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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,[@R_934_6964@,: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

大佬总结

以上是大佬教程为你收集整理的ruby-on-rails – 在已毁坏的嵌套模型栏中的validates_uniqueness_of全部内容,希望文章能够帮你解决ruby-on-rails – 在已毁坏的嵌套模型栏中的validates_uniqueness_of所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。