2

I am currently doing a project and in our project there's 2 table/classes ActivityType and Activity. Also in this project, we've use a gem called rails admin. The administrator can't delete a activity type if there's an activity type used in the activity.

Activity

class Activity < ApplicationRecord
  belongs_to :activity_type
end

Activity Type

class ActivityType < ApplicationRecord
  has_many :activities
before_destroy :ensure_has_no_activity_type

  private

  def ensure_has_no_activity_type
      unless activities.count == 0
       errors[:base] << "cannot delete activity type that has activity"
       return false
    end
  end
end

Question: How can I check if there's a child in activity? Is there something wrong in my code?

Angel
  • 966
  • 4
  • 25
  • 60

1 Answers1

3

This is what i meant

def ensure_has_no_activity_type
  if activities.present?
    errors.add(:base, 'Cannot delete activity type that has activity')
    throw(:abort)
  end
end
Md. Farhan Memon
  • 6,055
  • 2
  • 11
  • 36
  • It didn't work, correct me if I am wrong.. :base is the name of the model right? I also tried to use errors.add(:base, 'message: Cannot delete activity type that has activity') – Angel May 11 '17 at 04:48
  • remove quotes, message is key: .`errors.add(:base, message: 'Cannot delete activity type that has activity')` http://api.rubyonrails.org/classes/ActiveModel/Errors.html – Md. Farhan Memon May 11 '17 at 04:51
  • 1
    I also tried errors.add(:base, message: "Cannot delete activity type that has activity") didnt change.. I restart my server too – Angel May 11 '17 at 05:27
  • what do you mean by didn't change? – Md. Farhan Memon May 11 '17 at 05:29
  • if you want your rails admin to display that message, that's a flash message which needs to be overridden, that seems to be whole different question. By the above method you will get message in `object.errors.message`. – Md. Farhan Memon May 11 '17 at 05:38
  • Thank you for your effort again sir.. God Bless :) – Angel May 11 '17 at 06:34
  • have you found a way to show the custom message on rails admin when the validation fails? – Yamit May 08 '20 at 20:57