Varis Darasirikul
Varis Darasirikul

Reputation: 4177

How can i return some message if before_validation method is false by Sinatra

I want to return some message that tell the user their password is not match with the confirm password field.

This is my code

post '/signup' do
    user = User.new(params[:user])
    if user.create_user
        "#{user.list}"
    else
        "password not match"
    end
end

require 'bcrypt'

class User < ActiveRecord::Base
    include BCrypt
    # This is Sinatra! Remember to create a migration!

    attr_accessor :password

    validates :username, presence: true, uniqueness: true
    validates :email, :format => { :with => /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i ,
    :message => "Email wrong format" }
    validates :email, uniqueness: true,presence: true
    validates :encrypted_password, presence: true
    validates :encrypted_password, length: { minimum: 6 }

    before_validation :checking_confirm_password

    def initialize(signup = {})
        #@signup = signup
        super()
        @username = signup["username"]
        @email = signup["email"]
        @password = signup["password"]
        @confirm_password = signup["confirm_password"]
    end

    def create_user
        p_p = Password.create(@password)
        p_h ||= Password.new(p_p)
        user_hash = {:username => @username,:email => @email, :encrypted_password => p_h}

        return User.create(user_hash)

    end

    def list
        User.all
    end

    private

    def checking_confirm_password
        if @password != @confirm_password
            return false
        end
    end

end

So how can i specific the message that will send back to the user, if their password is not match or the validation fail before create the dada?

Thanks!

Upvotes: 1

Views: 211

Answers (1)

Dani
Dani

Reputation: 1022

The validations populate @user.errors with all validation errors with all validation errors by field, so you can easily return all validation errors at once like so:

post '/signup' do
  user = User.new(params[:user])
  if user.create_user
    "#{user.list}"
  else
    user.errors.full_messages
  end
end

Have a look at: http://edgeguides.rubyonrails.org/active_record_validations.html#working-with-validation-errors

Upvotes: 1

Related Questions