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
因此,虽然集合正确地与子文件夹相关联,但它在保存之前不会正确触发验证。 建议?     
已邀请:
我可以想到解释它的唯一方法是在分配collection_id之前调用验证,这是由于您使用的语法。也许试试吧
Folder.create(:collection => @collection, :name => 'example')
并看看它是否有任何改变。     
卫生署。 我的
associate_collection
回调需要发生
before_validation
,而不是
before_create
。 固定。谢谢你找人!     

要回复问题请先登录注册