views:

21

answers:

2

Hello, I'm trying to prevent a record that has a relationship to another record from being deleted. I can stop the deletion but not send a flash message as I had hoped!

class Purchaseitem < ActiveRecord::Base
  before_destroy :check_if_ingredient

  ...

  def check_if_ingredient
    i = Ingredient.find(:all, :conditions => "purchaseitem_id = #{self.id}")
      if i.length > 0
        self.errors.add(:name)
      flash.now[:notice] = 
        "#{self.name} is in use as an ingredient and cannot be deleted"
      return false
    end
  end

This will prevent a the delete wihthout the flash line, and when I add it I get:

undefined local variable or method `flash' for #

Any help would be much appreciated!

+2  A: 

Manipulation of the flash belongs in the controller.

Your model should return true/false from check_if_ingredient and the controller should render the flash message based upon the return value of check_if_ingredient

Steve Weet
A: 

You should do it in your controller.

# controller
if @purchaseitem.destroy
   flash.now[:notice] = 
      "#{@purchaseitem.name} was successfully deleted"
else
   flash.now[:notice] = 
      "#{@purchaseitem.name} is in use as an ingredient and cannot be deleted"
end
j.