0

I have a field in a model that is serialized and when I attempted to validates the uniqueness of it, it doesn't work. (Still on Rails 2.3 on this app)

app/models/foo.rb

class foo < ActiveRecord::Base

   serialize :rules

   validates_uniqueness_of :rules

end

I have attempted to store the content in a hash field instead and validate the content hash's uniqueness. Then I ran to another problem of the order of the callbacks.

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

However, having looked at the Active Record callbacks order, before_save is executed after validation, so it will always be valid because the default value is nil and after that it's updated to the new content hash.

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

Maybe I'm not thinking straight, any solution to this?

Many thanks in advance.

J Fong
  • 1,359
  • 1
  • 9
  • 11

1 Answers1

1

Try this:

 before_validation :update_content_hash
Rahul Tapali
  • 9,887
  • 7
  • 31
  • 44