fxe
fxe

Reputation: 575

Rails validate field

i have followin the http://ruby.railstutorial.org/

class User < ActiveRecord
  attr_accessible ..., :password, :password_confirmation
  has_secure_password

  validates :password, :presence => true,
                       :length => { :minimum => 6 }
  validates :password_confirmation, :presence => true

  ....
end

the problem is to create a new user this works fine, both passwords must be present and they need to match, when i update it requires me to provide the password

for example if another controller wants to change any field of User i must provide a password because otherwise i will not be able to update.

how can i formulate a contition to only require password/password_confirmation when creating the model or doing password update ?

Upvotes: 0

Views: 1218

Answers (2)

Tom Harrison
Tom Harrison

Reputation: 14068

Rails supports conditional validations, e.g. in your User model

validates :password_confirmation, :presence => true, :if => :new_password

def new_password
  current_user and current_user.changing_password?
end

You would need to figure out in the new_password method how to tell whatever conditions are true when you want to validate.

See: http://railscasts.com/episodes/41-conditional-validations

Upvotes: 1

hd1
hd1

Reputation: 34677

If you're using rails3, you can skip validations. From the docs:

The following methods skip validations, and will save the object to the database regardless of its validity. They should be used with caution.

  • decrement!
  • decrement_counter
  • increment!
  • increment_counter
  • toggle!
  • touch
  • update_all
  • update_attribute
  • update_column
  • update_counters

Note that save also has the ability to skip validations if passed :validate => false as argument. This technique should be used with caution.

Basically, use find to find the appropriate user, update whatever fields you want, user.save!(:validate=>false), and Bob's your uncle!

Upvotes: 1

Related Questions