no password_confirmation on create but need it during update (authlogic)
I am q开发者_JAVA技巧uite new to rails and I am using authlogic for my authentication system. I want to have password_confirmation when user updates his profile, but not when he is signing up.
I figured out this config option
acts_as_authentic do |c|
c.require_password_confirmation=false
end
When I do this, it ignores password_confirmation during signup (which is fine) but while editing user profile, I want it to consider password_confirmation field. is there any method I can configure this?
As you have suspended the Authlogic based validation you can achieve this with a standard Rails model validation such as:
validates_presence_of :password_confirmation, :if => :password_required?
where the password_required?
is an optional model method, which tests if you want this validation for a given scenario.
UPDATE
As it seems that the c.require_password_confirmation=false
option means the password_confirmation
attribute is no longer automatically created then you need to approach the solution slightly differently. Create a virtual attribute manually and a custom validation for the specific case of profile updates. Something like this:
class User < ActiveRecord::Base
attr_accessor :password_confirmation
validate do |user|
unless user.new_record?
user.errors.add :password, "is required" if self.password.blank?
user.errors.add :password_confirmation, "is required" if self.password_confirmation.blank?
user.errors.add_to_base, "Password and confirmation must match" if self.password != self.password_confirmation
end
end
end
精彩评论