validates_each
The validates_each method evaluates each listed attribute against the associated block. The
current record, the attribute to be evaluated, and the current value associated with the attribute
are passed as parameters to the block. The following example uses validates_each to
ensure that the submitted account_name value is "Kevin":
Class Account < ActiveRecord::Base
validates_each :Account_Name do |rec, attr, val|
if val != "Kevin"
rec.errors.add(":Account_Name", "Account name must be Kevin!")
end
end
end
CHAPTER 4 ?– CORE FEATURES OF ACTIVE RECORD 83
You can also specify a few options with validates_each, :on, :allow_nil, and :if. The :on
option allows you to specify if the validation should occur :on => :save, :on => :create, or on
=> :update. Here??™s our example again, but limited to just updates:
Class Account < ActiveRecord::Base
Validates_each :Account_Name, :on => :update do |rec, attr, val|
If val != "Kevin"
Rec.errors.add(":Account_Name", "Account name must be Kevin!")
end
end
end
The :allow_nil option (:allow_nil => true or :allow_nil => false) lets you perform the
validation block for those attributes listed that do or do not have nil values.
Pages:
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