validates_uniqueness_of在销毁的嵌套模型轨道中 [英] validates_uniqueness_of in destroyed nested model rails

查看:79
本文介绍了validates_uniqueness_of在销毁的嵌套模型轨道中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Project模型,该模型接受Task的嵌套属性.

I have a Project model which accepts nested attributes for 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

任务模型中的唯一性验证在更新Project时出现问题.

Uniqueness validation in Task model gives problem while updating Project.

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

In edit of project i delete a task T1 and then add a new task with same name T1, uniqueness validation restricts the saving of Project.

参数哈希看起来像

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

在销毁旧任务之前已完成对任务的验证.因此验证失败.有什么主意如何进行验证以使其不认为任务被销毁了吗?

Validation on task is done before destroying the old task. Hence validation fails.Any idea how to validate such that it doesn't consider task to be destroyed?

推荐答案

Andrew France在此

Andrew France created a patch in this thread, where the validation is done in memory.

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

这篇关于validates_uniqueness_of在销毁的嵌套模型轨道中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆