diff options
author | Vijay Dev <vijaydev.cse@gmail.com> | 2013-02-15 22:06:17 +0530 |
---|---|---|
committer | Vijay Dev <vijaydev.cse@gmail.com> | 2013-02-15 22:06:17 +0530 |
commit | 0c145448c42e811f9241e1634ecd2d60ddefff3a (patch) | |
tree | fb56c9870510de868250c4e027a11ebcead6e53f /guides/source/active_record_validations.md | |
parent | 520a16caad3d89da734c0f5bc14b8c16090f891f (diff) | |
parent | 2008fe606b6096e4b8ad9c03e03b0d11b94605cd (diff) | |
download | rails-0c145448c42e811f9241e1634ecd2d60ddefff3a.tar.gz rails-0c145448c42e811f9241e1634ecd2d60ddefff3a.tar.bz2 rails-0c145448c42e811f9241e1634ecd2d60ddefff3a.zip |
Merge branch 'master' of github.com:lifo/docrails
Conflicts:
guides/source/upgrading_ruby_on_rails.md
Diffstat (limited to 'guides/source/active_record_validations.md')
-rw-r--r-- | guides/source/active_record_validations.md | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md index eaa47d4ebf..32641d04c1 100644 --- a/guides/source/active_record_validations.md +++ b/guides/source/active_record_validations.md @@ -618,6 +618,35 @@ class GoodnessValidator < ActiveModel::Validator end ``` +Note that the validator will be initialized *only once* for the whole application +life cycle, and not on each validation run, so be careful about using instance +variables inside it. + +If your validator is complex enough that you want instance variables, you can +easily use a plain old Ruby object instead: + +```ruby +class Person < ActiveRecord::Base + validate do |person| + GoodnessValidator.new(person).validate + end +end + +class GoodnessValidator + def initialize(person) + @person = person + end + + def validate + if some_complex_condition_involving_ivars_and_private_methods? + @person.errors[:base] << "This person is evil" + end + end + + # … +end +``` + ### `validates_each` This helper validates attributes against a block. It doesn't have a predefined |