"1","name" => "T1", "_-6ren">
gpt4 book ai didi

ruby-on-rails - validates_uniqueness_of在销毁的嵌套模型 rails 中

转载 作者:行者123 更新时间:2023-12-03 13:32:44 25 4
gpt4 key购买 nike

我有一个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


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

在项目编辑中,我删除任务T1,然后添加一个具有相同名称T1的新任务,唯一性验证限制了项目的保存。

参数哈希看起来像

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


在销毁旧任务之前已完成任务验证。因此验证失败。有什么想法可以进行验证,使其不认为任务被销毁了吗?

最佳答案

Andrew France在此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

关于ruby-on-rails - validates_uniqueness_of在销毁的嵌套模型 rails 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2772236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com