views:

34

answers:

3

I have looked through the Ruby on Rails guides and I can't seem to figure out how to prevent someone from deleting a Parent record if it has Children. For example. If my database has CUSTOMERS and each customer can have multiple ORDERS, I want to prevent someone from deleting a customer if it has any orders in the database. They should only be able to delete a customer if it has no orders.

Is there a way when defining the association between models to enforce this behavior?

A: 

Try using filters to hook in custom code during request processing.

Joe
A: 

One possibility would be to avoid providing your users a link to deletion in this scenario.

link_to_unless [email protected]?

Another way would be to handle this in your controller:

if [email protected]?
  flash[:notice] = "Cannot delete a customer with orders"
  render :action => :some_action
end

Or, as Joe suggests, before_filters could work well here and would probably be a much more DRY way of doing this, especially if you want this type of behavior for more models than just Customer.

Samo
+3  A: 

You could do this in a callback:

class Customer < ActiveRecord::Base
  has_many :orders
  before_destroy :check_for_orders

  private

  def check_for_orders
    if orders.count > 0
      errors.add_to_base("cannot delete customer while orders exist")
      return false
    end
  end
end
zetetic
This is the best way. It's the cleanest, and it's exactly where I would look for such a filter if I was working on your code. Returning "false" in the callback is what tells rails not to proceed with the action.
Jaime Bellmyer
`has_any...?` :)
Joe
Thanks, Joe. No, I didn't invent a new association type...
zetetic