Rails 4.2 - 依赖::restrict_with_error - 访问错误 [英] Rails 4.2 - dependent: :restrict_with_error - access errors

查看:39
本文介绍了Rails 4.2 - 依赖::restrict_with_error - 访问错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

:restrict_with_error 导致错误添加到所有者如果有关联的对象rails 关联基础

:restrict_with_error causes an error to be added to the owner if there is an associated object rails association basics

我已将以下内容添加到我的代码中:

I have added the following to my code:

class Owner < ActiveRecord::Base
  has_many :things, dependent: :restrict_with_error
end

我的理解是,当我尝试删除具有依赖事物所有者时,应该会引发错误.在 owners_controller 中的显示操作中,我尝试访问错误但找不到它们:

My understanding is when I try to delete an Owner that has dependent things then an error should be raised. In my show action in the owners_controller I try to access the errors but can not find them:

def show
  @owner = Owner.find(params[:id])
  @owner.errors
end

更新 - 删除代码

def destroy
  @owner = Owner.find(params[:id])
  @owner.destroy
  flash[:notice] = "Owner Deleted Successfully"
  respond_with(@owner)
end

推荐答案

给定你的代码...

def destroy
  @owner = Owner.find(params[:id])
  @owner.destroy
  flash[:notice] = "Owner Deleted Successfully"
  respond_with(@owner)
end

def show
  @owner = Owner.find(params[:id])
  @owner.errors
end

当您尝试访问错误时,不会有任何错误.

At the point you are trying to access errors, there will not be any.

错误是暂时的.它们不会持久化对象,也不会交叉请求.它们仅存在于生成错误的同一请求中的模型上.

Errors are temporary. They do not persist with the object, and they do not cross requests. They only exist on the model in the same request that generated the errors.

您的代码中唯一可用的错误点是destroy内,之后您调用@owner.destroy.它们永远不会在您的 show 操作中可用.

The only point in your code at which errors will be available is inside destroy, after you call @owner.destroy. They will never be available inside your show action.

def destroy
  @owner = Owner.find(params[:id])
  @owner.destroy
  # You must check for @owner.errors here
  flash[:notice] = "Owner Deleted Successfully"
  respond_with(@owner)
end

这篇关于Rails 4.2 - 依赖::restrict_with_error - 访问错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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