1

Is there a way to permit deletion of a record ONLY if it has no associations?

For example we can have rooms and events. For some reason RoomX is not supposed to be used any more & can be deleted.

Task: User can not delete @room until validates: @room has no Events.

room.rb:

class Room < ActiveRecord::Base
  has_many :events
  def to_s
    name
  end
end

event.rb:

class Event < ActiveRecord::Base
  belongs_to :room
end

Do you have any ideas/solutions?

  • No code provided so it's hard to provide a full solution here, but based on what you've described it's easily done by do some checking to make sure the rooms are transferred before deleting the object. – nayiaw Mar 10 '16 at 09:56
  • Possible duplicate of [How do I prevent deletion of parent if it has child records?](http://stackoverflow.com/questions/4054112/how-do-i-prevent-deletion-of-parent-if-it-has-child-records) – potashin Mar 10 '16 at 10:22

2 Answers2

2

You can use before_destroy validation and check if no association is still existing

class Room < ActiveRecord::Base

 before_destroy :check_for_associations

  def events?
    events.any?
  end

  private

  def check_for_associations
    if events?
      errors[:base] << "cannot delete : events are still planned"
      false
    end
  end
end
XavM
  • 863
  • 9
  • 22
1

You haven't given much to go on but here is a very simple implementation that you could use in a view:

if room.events.present?
  "You can't delete this"
else
 link_to room_path(@room), method: :delete
end

This would deal with the View layer validation - but you should also look to validate this in your model and again at the Database layer.

In your model you could look to add a before_destroy validation to make the same check as above.

before_destroy :check_whether_room_has_events

def check_whether_room_has_events
  return true if room.events.count == 0
  errors.add(:base, "Cannot delete room with events")
  return false
end

I believe this last bit is correct but have not tested it.

Ben Hawker
  • 949
  • 8
  • 15