Layered Verification in Rails

I am working on a Rails application that existing users can invite to participate in additional members. The problem is that the User model exists in different states and different states require a different set of information.

For example, John is a member of the site and invites Mary. John enters Mary's name and email address, a user record is created in the database for Mary, and an invitation email is sent. However, after she joins, the required data set changes, and we require that she enter additional information (for example, password).

I'm still learning Ruby on Rails, and I see no way to deal with this using the standard validates_presence_of , validates_format_of , etc. validation methods. Can someone point me in the right direction

+7
validation ruby-on-rails
source share
2 answers

The easiest way to use :if as follows:

 class User < ActiveRecord::Base validate_presence_of :name validate_presence_of :age, :if => Proc.new { |user| user.signup_step >= 2 } # ... etc end 

or

 class User < ActiveRecord::Base validate_presence_of :name validate_presence_of :age, :if => :registering? def registering? signup_step >= 2 end end 

You can also use the validate method to determine any complex, custom logic. For example:

 class User < ActiveRecord::Base validate :has_name_and_email_after_invitation validate :has_complete_profile_after_registration def has_name_and_email_after_invitation if ... # determine if we're creating an invitation # step 1 validation logic here end end def has_complete_profile_after_registration if ... # determine if we're registering a new user # step 2 validation logic here end end end 

(In the example above, you can really define validation rules in has_name_and_email_after_invitation with regular calls validates_xxx_of , because they should also be applied in step 2, but using two methods for the individual steps gives you maximum flexibility.)

+9
source share

And for DRYin'up, your code is a bit, you can use with_options , for example:

 class Example < ActiveRecord::Base [...] def registering? signup_step >= 2 end with_options(:if => :registering?) do |c| c.validates_presence_of :name end with_options(:unless => :registering?) do |c| c.validates_presence_of :contact_details end [...] end 

Find out more about with_options here:

http://apidock.com/rails/v2.3.2/Object/with_options

There's even a screencast from RailsCasts:

http://railscasts.com/episodes/42-with-options

+5
source share

All Articles