Rails 5 throw abort:如何设置错误消息? [英] Rails 5 throw abort : how do I setup error messages?

查看:55
本文介绍了Rails 5 throw abort:如何设置错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 引入了这种 throw(:abort) 语法,但现在我如何获得有意义的销毁错误?

Rails has introduced this throw(:abort) syntax, but now how do I get meaningful destroy errors ?

对于验证错误,可以这样做

For validation errors one would do

if not user.save
  # => user.errors has information

if not user.destroy
  # => user.errors is empty

这是我的模型

class User

  before_destroy :destroy_validation,
    if: :some_reason

  private

  def destroy_validation
    throw(:abort) if some_condition
  end

推荐答案

您可以将 errors.add 用于您的类方法.

You can use errors.add for your class method.

用户模型:

def destroy_validation
  if some_condition
    errors.add(:base, "can't be destroyed cause x,y or z")
    throw(:abort)
  end
end

用户控制器:

def destroy
  if @user.destroy
    respond_to do |format|
      format.html { redirect_to users_path, notice: ':)' }
      format.json { head :no_content }
    end
  else
    respond_to do |format|
      format.html { redirect_to users_path, alert: ":( #{@user.errors[:base]}"}
    end
  end
end

这篇关于Rails 5 throw abort:如何设置错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆