我有一个项目模型,该模型接受任务的嵌套属性。

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的新任务,唯一验证限制了项目的保存。

参数哈希看起来像

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

在销毁旧任务之前,要对任务进行验证。因此,验证失败。任何想法如何验证它不考虑被摧毁的任务?

有帮助吗?

解决方案

安德鲁·法国(Andrew France)在此创建了一个补丁 线, ,在内存中进行验证。

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

其他提示

据我了解,在我的情况下,雷纳(Reiner)在记忆中验证的方法是不可行的,因为我有很多“书籍”,500k且成长。如果您想将全部记忆成真,那将是一个很大的打击。

我想到的解决方案是:

通过将以下内容添加到DB/Migrate/::

  add_index :tasks [ :project_id, :name ], :unique => true

在控制器中,将保存或update_attributes放入交易中,并挽救数据库异常。例如,

 def update
   @project = Project.find(params[:id])
   begin
     transaction do       
       if @project.update_attributes(params[:project])
          redirect_to(project_path(@project))
       else
         render(:action => :edit)
       end
     end
   rescue
     ... we have an exception; make sure is a DB uniqueness violation
     ... go down params[:project] to see which item is the problem
     ... and add error to base
     render( :action => :edit )
   end
 end

结尾

对于Rails 4.0.1,此问题被标记为该拉的请求固定, https://github.com/rails/rails/pull/10417

如果您有一个带有唯一字段索引的表,并且标记了销毁记录,并且构建具有与唯一字段相同的值的新记录,那么当您调用保存时,数据库级别唯一索引错误将被丢弃。

就我个人而言,这仍然对我不起作用,所以我认为它还没有完全固定。

Rainer Blessing的答案很好。但是,当我们可以标记哪些任务复制时,这是更好的。

class Project < ActiveRecord::Base
  has_many :tasks, inverse_of: :project

  accepts_nested_attributes_for :tasks, :allow_destroy => :true
end

class Task < ActiveRecord::Base
  belongs_to :project

  validates_each :name do |record, attr, value|
    record.errors.add attr, :taken if record.project.tasks.map(&:name).count(value) > 1
  end
end

参考

你为什么不使用:范围

class Task < ActiveRecord::Base
  validates_uniqueness_of :name, :scope=>'project_id' 
end

这将为每个项目创建独特的任务。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top