Rails 4.2 - dependent :: restrict_with_error - access errors

: restrict_with_error causes an error to be added to the owner if there is a related Rail Association Basics object

I added the following to my code:

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

My understanding is that when I try to remove the Owner that has dependent things , then an error occurs. In my show action in owners_controller I try to access errors, but cannot find them:

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

UPDATE - Delete code

 def destroy @owner = Owner.find(params[:id]) @owner.destroy flash[:notice] = "Owner Deleted Successfully" respond_with(@owner) end 
+5
source share
1 answer

Given your code ...

 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 moment when you are trying to access errors, they will not be.

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

The only point in your code where errors will be available 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 
+6
source

Source: https://habr.com/ru/post/1215494/


All Articles