Answer the question
In order to leave comments, you need to log in
How to use has_many :posts, dependent:?
I have a User model
class User < ActiveRecord::Base
has_many :posts, dependent: :destroy
end
class User < ActiveRecord::Base
has_many :posts, dependent: :restrict_with_exception
end
class UsersController < ApplicationController
...
def destroy
@user.destroy
flash[:danger] = "Success"
redirect_to users_path
rescue => e
flash[:danger] = "Error"
redirect_to @user
end
...
end
Answer the question
In order to leave comments, you need to log in
In this case, I would recommend not to use exceptions for management. Moreover, for your task, the :restrict_with_error
In source rails parameter is more suitable:
when :restrict_with_error
unless empty?
record = klass.human_attribute_name(reflection.name).downcase
owner.errors.add(:base, :"restrict_dependent_destroy.many", record: record)
false
end
else
if @user.destroy
...
else
....
end
before_destroy
directive, and either do an explicit check there, or throw an exception explicitly. The main thing in a negative scenario is not to forget to return false.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question