gpt4 book ai didi

ruby - 验证嵌套表单中子对象的唯一性无法正常工作

转载 作者:数据小太阳 更新时间:2023-10-29 07:34:41 25 4
gpt4 key购买 nike

我对 Rails 中的范围唯一性验证有疑问。如果我尝试直接在子模型中创建一个具有我不想重复的相同属性集的新对象,它工作正常,但是当我尝试创建一个具有两个不唯一的子项的父项时,验证没有被触发。

背景

我在 Rails 3.2 中有一个应用程序,其 View 在 HAML 中使用 simple_form。

我有两个模型:PageProperty。一个页面可以有很多属性,它接受属性的嵌套属性。

我想验证一个页面不能有两个同名的属性:

#app/models/page.rb
class Page < ActiveRecord::Base
has_many :properties
accepts_nested_attributes_for :properties, :allow_destroy => :true
end


#app/models/property.rb
class Property < ActiveRecord::Base
belongs_to :page
VALID_PROPERTIES = %w(id text name xpath class css)
validates :name, :inclusion => VALID_PROPERTIES, :uniqueness => {:scope => :page_id}
end

当然,该属性还有一个page_id属性。

正如我所说,当通过其表单创建新属性时,验证有效。如果我尝试创建一个具有相同名称和相同 page_id 的新属性,Rails 会告诉我该名称已被占用。

问题

如果我创建一个新页面,并通过嵌套表单分配各种属性,我可以绕过此验证。当 page_id 和 property_id 的组合不存在于数据库中时,这似乎只是一个问题,因此例如,如果我编辑一个已经保存了属性的页面模型,并且我尝试添加一个新的同名,现在触发验证。

最佳答案

我会尝试使用 validates_associated :

class Page < ActiveRecord::Base
has_many :properties
accepts_nested_attributes_for :properties, :allow_destroy => :true
validates_associated :properties
end

更新

关于验证状态的 Rails 指南:

The validation happens by performing an SQL query into the model’s table, searching for an existing record with the same value in that attribute.

您正在创建的 2 Properties 对象在数据库中尚不存在,因此唯一性验证无法进行。您应该尝试使用自定义验证

class Property < ActiveRecord::Base
#...
validate :name, :name_uniqueness

def name_uniqueness
self.page.properties.select {|p| p.key == self.key}.size == 1
end
end

关于ruby - 验证嵌套表单中子对象的唯一性无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9705508/

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