Forum: Ruby on Rails validates :on 2

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Mohammad (Guest)
on 2006-05-04 08:39
Hello, I need to have this for :create and :login how do I do so
validates_presence_of :login, :password, :password_confirmation,
:user_name, :email, :on => :create

I do need it to be off in a number of places though
Mohammad (Guest)
on 2006-05-04 16:41
Anyone know how?
Mohammad (Guest)
on 2006-05-04 23:14
bump
Jon F. (Guest)
on 2006-05-05 05:36
Mohammad wrote:
> Hello, I need to have this for :create and :login how do I do so
> validates_presence_of :login, :password, :password_confirmation,
> :user_name, :email, :on => :create
>
> I do need it to be off in a number of places though

You should be able to use the validate_on_create method for this, or
alternatively just list the requirements one after the other with the
:on parameter (though that may be venturing into the region of
unmaintainable code).

See the following docs:
http://api.rubyonrails.com/classes/ActiveRecord/Va...

Example:

def validate_on_create
    errors.add_on_empty %w( login password password_confirmation
user_name email )
end

To selectively turn it off, you can apply whatever conditional
structures you'd like to use within the validate_on_create method.
Alternatively, I've seen the following setup used:

  validates_presence_of     :login
  validates_presence_of     :password, :if => :password_required?
  validates_presence_of     :password_confirmation, :if =>
:password_required?

Where :password_required is a protected method in the model which
determines if the password is actually needed at that time.

  def password_required?
    crypted_password.blank? or not password.blank?
  end

The latter two examples are directly pulled from Geoffrey Grosenbach's
Gullery app. Check it out:
http://www.nubyonrails.com/pages/gullery
This topic is locked and can not be replied to.