Rails 4.2 - dependent :: restrict_with_error - 访问错误

时间:2015-03-17 03:39:20

标签: ruby-on-rails ruby-on-rails-4

  

:如果存在关联对象,restrict_with_error会将错误添加到所有者   rails association basics

我在代码中添加了以下内容:

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

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

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

1 个答案:

答案 0 :(得分:6)

鉴于你的代码......

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

在您尝试访问错误时,不会有任何错误。

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

代码中唯一可以提供错误的点是destroy 内,之后调用@owner.destroy。它们永远不会在show行动中提供。

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