0

我在模型中有一个序列化的字段,当我尝试验证它的唯一性时,它不起作用。(在这个应用程序上仍然使用 Rails 2.3)

应用程序/模型/foo.rb

class foo < ActiveRecord::Base

   serialize :rules

   validates_uniqueness_of :rules

end

我试图将内容存储在哈希字段中并验证内容哈希的唯一性。然后我遇到了回调顺序的另一个问题。

require 'digest/md5'

class foo < ActiveRecord::Base

   before_save :update_content_hash

   validates_uniqueness_of :content_hash

   def update_content_hash
      self.content_hash = OpenSSL::Digest::SHA1.hexdigest(self.rules.flatten)

   end
end

但是,查看 Active Record 回调顺序后,before_save 是验证后执行的,因此它将始终有效,因为默认值为 nil,之后它会更新为新的内容哈希。

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

也许我没有想清楚,有什么解决办法吗?

提前谢谢了。

4

1 回答 1

1

尝试这个:

 before_validation :update_content_hash
于 2013-02-21T16:45:25.243 回答