Rails:为什么fail_uniqeness失败仍然允许保存?
- 根据进一步测试重写的问题 -
所以,我的应用程序has_many文件夹属于收藏集。
文件夹是嵌套的,它们也可以属于另一个文件夹。
我想验证每个集合中文件夹名称的唯一性。当我在顶层创建文件夹时,这可以工作,但是当我在较低级别创建它时,它不起作用。以下是模型:
class Folder < ActiveRecord::Base
# CALLBACKS
before_create :associate_collection
# RELATIONSHIPS
belongs_to :collection
belongs_to :parent, :class_name => 'Folder'
has_many :subfolders, :class_name => 'Folder', :foreign_key => :parent_id
# VALIDATIONS
validates_presence_of :name
validates_uniqueness_of :name, :scope => :collection_id
private
def associate_collection
if self.collection.nil?
self.collection = self.parent.collection
end
end
end
class Collection < ActiveRecord::Base
# RELATIONSHIPS
has_one :root_folder, :class_name => 'Folder', :conditions => { :parent_id => nil }
has_many :folders
# CALLBACKS
after_create :setup_root_folder
private
def setup_root_folder
self.create_root_folder(:name=>'Collection Root')
self.save!
end
end
这是控制台中发生的事情的简略示例:
c = Collection.new(:name=>'ExampleCollection')
#<Collection id: 1>
root = c.root_folder
#<Folder id: 1, collection_id: 1>
f1 = root.subfolders.create(:name=>'Test')
#<Folder id: 2 collection_id: 1>
f1.valid?
# TRUE
f2 = root.subfolders.create(:name=>'Test')
#<Folder id: 3 collection_id: 1>
f2.valid?
# FALSE
f1.valid?
# FALSE
因此,虽然集合正确地与子文件夹相关联,但它在保存之前不会正确触发验证。
建议?
没有找到相关结果
已邀请:
2 个回复
焙恍挝厂熄
并看看它是否有任何改变。
涸坍饺
回调需要发生
,而不是
。 固定。谢谢你找人!