Rails:如何检查模型对象的验证错误?

时间:2014-11-22 04:54:13

标签: ruby-on-rails

我试图让我的应用程序显示ActiveRecord可能引发的任何验证错误。我的问题是我不知道如何在没有崩溃的情况下检查我的对象是否有错误。我正在做@user.errors.any?,但是这不起作用,因为如果没有任何错误,它将调用@user上的错误并且为空并导致错误。如何在没有Rails崩溃的情况下检查@user对象是否有错误?

  def update
    @user = current_user.update(user_params)
    if @user.errors.empty?
      flash[:notice] = "Update Successful"
    else
      flash[:notice] = "Update Failed"
    end
    redirect_to "/"
  end

2 个答案:

答案 0 :(得分:0)

即使没有错误,

@user.errors也应该返回ActiveModel::Errors。 如果要在可能是对象或零的内容上调用方法,可以使用try方法 http://apidock.com/rails/Object/try

答案 1 :(得分:0)

您不需要@user,因为您已经拥有current_user(此外,您还要重定向,因此不会使用该分配)。此外,您使用returns false when invalid的方法,因此您不需要额外的检查。

  def update
    flash[:notice] = if current_user.update(user_params)
      'Update Successful'
    else
      'Update Failed'
    end
    redirect_to '/' # Try redirect_to root_path
  end

如果出于某种原因,current_user为nil,请将控制器(或至少是操作)置于身份验证之后,或者使用类似的东西(甚至更好,the null object pattern):

  def update
    flash[:notice] = if current_user && current_user.update(user_params)
      'Update Successful'
    else
      'Update Failed'
    end
    redirect_to '/' # Try redirect_to root_path
  end