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

:restrict_with_error如果存在关联的对象rails关联基础,则会将错误添加到所有者

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

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 

鉴于你的代码……

 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 

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

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

在调用@owner.destroy 之后 ,代码中唯一可以提供错误的点是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