validation - Is there a better way to validate in Rails? -
validation - Is there a better way to validate in Rails? -
in model have validations check presence of "password" , "password_confirmation" fields. while creating model, validations run fine. during updating model, while updating grouping of specific fields, validations seem called on whole model. , dont pass in "password" , "password_confirmation" fields every time, validation fails.
at first thought validate 2 fields "on :create" want give alternative update password well. in case validations wont called during update of fields.
so, there way handle problem?
the next model:
class consumer < activerecord::base attr_accessor :password, :password_confirmation mount_uploader :image, profileimageuploader email_regex = /\a([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i pass_regex = /\a[a-za-z0-9]{8,16}\z/ validates :email, presence: {message: "email cannot blank!", on: :create}, format: {with: email_regex, message: "email invalid!"} validate :unique_email?, on: :create validates :password, presence: {message: "password cannot blank!"}, confirmation: {message: "passwords not match!"}, format: {with: pass_regex, message: "password invalid!"} validates :password_confirmation, presence: {message: "retype password!"} validates :fullname, presence: {message: "name cannot empty!"} before_save :encrypt_password def authenticate pass new_hash = bcrypt::engine.hash_secret pass, self.password_salt if new_hash === self.password_hash homecoming true end false end def encrypt_password if password.present? self.password_salt = bcrypt::engine.generate_salt self.password_hash = bcrypt::engine.hash_secret password, password_salt end end end
conditional validations
was going suggest utilize sort of conditional validations, follows (then read comments):
#app/models/consumer.rb class consumer < activerecord::base ... validates :password_confirmation, presence: {message: "retype password!"}, if: proc.new {|a| a.password.present? } end this best can provide particular situation - i've not created password signup / authentication procedure myself (always relied on other classes), if wanted utilize has_secure_password etc - i'll have update reply help
ruby-on-rails validation
Comments
Post a Comment