Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4.2 - dependent: :restrict_with_error - access errors

: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

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

UPDATE - Delete Code

def destroy
  @owner = Owner.find(params[:id])
  @owner.destroy
  flash[:notice] = "Owner Deleted Successfully"
  respond_with(@owner)
end
like image 545
Marklar Avatar asked Mar 17 '15 03:03

Marklar


1 Answers

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 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.

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
like image 65
meagar Avatar answered Oct 19 '22 23:10

meagar