'Rails Discard gem - before_discard, custom error

I have a blog. I have Articles with Posts. Instead of destroying, I want to base on discarding everything. I expect that you need to archive all posts before archiving the article. When this condition is not met, I want to get an error 404 and then use it as JSON in my view. I am currently getting error 500 with the default message: "Request failed with status code 500" and in backend only: Discard::RecordNotDiscarded (Failed to discard the record).

Here is my article model:

class Article < ApplicationRecord
  include Discard::Model
  has_many :comments, dependent: :destroy

  validates :title, presence: true
  before_discard :can_destroy?, prepend: true

  def can_destroy?
    if posts.kept.any?
      errors.add(:base, "First you have to archive all posts in this article")
      throw :abort
    end
  end
end


Solution 1:[1]

I want to get an error 404

404 is usually used when the record is not found, in your scenerio it exists so I suggest returning 422 (unprocessable entity) instead.

And to answer your original question - there are few options possible.

  1. Check if posts.kept.any? before calling discard.
  2. Use catch to handle the throw that you implemented.
  3. Raise an exception instead of using throw and rescue it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kamil Gwó?d?