: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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With