Method: Sequel::Plugins::ValidationClassMethods::ClassMethods#validates_each
- Defined in:
- lib/sequel/plugins/validation_class_methods.rb
permalink #validates_each(*atts, &block) ⇒ Object
Adds a validation for each of the given attributes using the supplied block. The block must accept three arguments: instance, attribute and value, e.g.:
validates_each :name, :password do |object, attribute, value|
object.errors.add(attribute, 'is not nice') unless value.nice?
end
Possible Options:
- :allow_blank
-
Whether to skip the validation if the value is blank.
- :allow_missing
-
Whether to skip the validation if the attribute isn’t a key in the values hash. This is different from allow_nil, because Sequel only sends the attributes in the values when doing an insert or update. If the attribute is not present, Sequel doesn’t specify it, so the database will use the table’s default value. This is different from having an attribute in values with a value of nil, which Sequel will send as NULL. If your database table has a non NULL default, this may be a good option to use. You don’t want to use allow_nil, because if the attribute is in values but has a value nil, Sequel will attempt to insert a NULL value into the database, instead of using the database’s default.
- :allow_nil
-
Whether to skip the validation if the value is nil.
- :if
-
A symbol (indicating an instance_method) or proc (which is used to define an instance method) skipping this validation if it returns nil or false.
- :tag
-
The tag to use for this validation.
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 |
# File 'lib/sequel/plugins/validation_class_methods.rb', line 194 def validates_each(*atts, &block) opts = (atts) blank_meth = db.method(:blank_object?).to_proc i = opts[:if] am = opts[:allow_missing] an = opts[:allow_nil] ab = opts[:allow_blank] blk = if i || am || an || ab if i.is_a?(Proc) i = Plugins.def_sequel_method(self, "validation_class_methods_if", 0, &i) end proc do |o,a,v| next if i && !validation_if_proc(o, i) next if an && Array(v).all?(&:nil?) next if ab && Array(v).all?(&blank_meth) next if am && Array(a).all?{|x| !o.values.has_key?(x)} block.call(o,a,v) end else block end tag = opts[:tag] atts.each do |a| a_vals = Sequel.synchronize{validations[a] ||= []} if tag && (old = a_vals.find{|x| x[0] == tag}) old[1] = blk else a_vals << [tag, blk] end end end |