Question

I have validation on uniqueness and I want skipping certain value or values(for example 0000):

validates_uniqueness_of :gtin, :scope => [:user_id, :item_id]

I'm tried to use next construction, but she don't work:

validates_uniqueness_of :gtin, :scope => [:user_id, :item_id], :unless => Proc.new{|base_item| base_item.gtin == '0000'}

How I can skip certain value or values? Thanks.

P.S. update!!! did not see a manual migration, which change behaviour

Était-ce utile?

La solution

using the :unless option is certainly the right way, but i think you get the whole object as proc argument so it should be

validates_uniqueness_of :gtin, :scope => [:user_id, :item_id], :unless => Proc.new{|obj| obj.gtin == '0000'}

Autres conseils

Not sure if this is a gotcha or not. Is the value of gtin a string or an integer? It looks like what your doing should work, but if it's an integer you would want to change to:

validates :gtin, :uniqueness => {:scope => [:user_id, :item_id]}, :unless => Proc.new{|base_item| base_item.gtin == 0000}

I'm trying to do the same thing, and I think I know what's wrong. The problem is, the if or unless "base_item" object refers to the value you're checking the uniqueness for, not the prospective match object.

Maybe you really do mean to check the item you're validating (in which case I'm barking up the wrong tree), but it seems more natural in the uniqueness case to want to exclude certain matches. For instance, I have a field is_deleted, and I want to allow a uniqueness violation if the matching object has been deleted.

I can't find any way to reference the matching object that was found in the proc. You can accomplish this by making your own a custom validation function though. For instance, if you want to validate the uniqueness of 'name', you might try something like this:

validate :full_validation
def full_validation
  matches = self.class.find_all_by_name(self.name).select {|match| match.id != self.id && match.is_deleted==false}
  return (matches.size>0)
end
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top