Ruby 如果Sinatra的before_验证方法为false,我如何返回一些消息

Ruby 如果Sinatra的before_验证方法为false,我如何返回一些消息,ruby,activerecord,sinatra,Ruby,Activerecord,Sinatra,我想返回一些消息,告诉用户他们的密码与确认密码字段不匹配 这是我的密码 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 includ

我想返回一些消息,告诉用户他们的密码与确认密码字段不匹配

这是我的密码

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
post'/signup'do
user=user.new(参数[:user])
如果user.create\u user
“#{user.list}”
其他的
“密码不匹配”
结束
结束
需要“bcrypt”
类用户{:with=>/\A[\w+\-.]+@[A-z\d\-]+(\.[A-z]+)*\.[A-z]+\z/i,
:message=>“电子邮件格式错误”}
验证:电子邮件,唯一性:真,存在性:真
验证:加密密码,状态:true
验证:加密的_密码,长度:{最小值:6}
验证前:检查\u确认\u密码
def初始化(注册={})
#@注册
超级()
@用户名=注册[“用户名”]
@电子邮件=注册[“电子邮件”]
@密码=注册[“密码”]
@确认密码=注册[“确认密码”]
结束
def创建用户
p_p=Password.create(@Password)
p|h | |=密码。新(p|p)
用户\u散列={:用户名=>@username,:email=>@email,:加密的\u密码=>p\u h}
返回User.create(User\u散列)
结束
定义列表
User.all
结束
私有的
def检查\u确认\u密码
如果@password!=@确认密码
返回错误
结束
结束
结束
那么我如何确定将发送回用户的消息, 如果他们的密码不匹配或在创建数据之前验证失败


谢谢

验证通过字段填充
@user.errors
所有验证错误和所有验证错误,因此您可以轻松地一次返回所有验证错误,如下所示:

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

请查看:

为什么即使密码不匹配或电子邮件不唯一,我也从未收到错误?@user3403614如何检查响应?您如何判断是否存在错误?在我添加的代码片段中,我们仍然返回HTTP状态200,这对AJAX回调(以及其他内容)有影响。如果这确实是您的情况,那么在发送响应之前添加一个
状态422
。现在我只想从User返回true或false。create(User\u hash)然后我可以在controllernow create\u User方法中检查它,即使我没有在表单中添加任何信息,它也总是返回true。