2010-06-07 65 views
1

我试图阻止与另一个记录有关系的记录被删除。我可以停止删除,但不会发送我希望的闪光消息!无法从模型方法发送Flash消息

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 

这将阻止该删除wihthout闪光灯线,当我添加它,我得到:

未定义的局部变量或方法'闪光”为#

任何帮助将不胜感激!

回答

4

操纵闪光灯属于控制器。

你的模型应该从check_if_ingredient返回真/假和控制器应该呈现基于check_if_ingredient

-1

的返回值,你应该这样做在你的控制器中的闪存消息。

# 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