R
R
railshello2014-07-15 10:00:46
Ruby on Rails
railshello, 2014-07-15 10:00:46

How to use has_many :posts, dependent:?

I have a User model

class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
end

How to use dependent so that it throws an error if entries exist?
If there are no posts, then you can delete the user !
I found the :restrict_with_exception parameter , but for some reason it doesn't work:
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

1 answer(s)
V
vladson4ik, 2014-07-15
@vladson4ik

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

In this case, you normally do
if @user.destroy
  ...
else 
....
end

There is another option to use the before_destroydirective, 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 question

Ask a Question

731 491 924 answers to any question