我想分配一个消息闪烁[:通知],在模型观察
I am trying to assign a message to flash[:notice] in a model observer.
这个问题已经被问:Ruby on Rails的:观察员和flash [:通知]消息
不过,我得到以下错误消息时,我尝试访问它在我的模型:
However, I get the following error message when I try to access it in my model:
undefined local variable or method `flash' for #<ModelObserver:0x2c1742c>
下面是我的code:
class ModelObserver < ActiveRecord::Observer
observe A, B, C
def after_save(model)
puts "Model saved"
flash[:notice] = "Model saved"
end
end
我知道这个方法被调用,因为节省模式被打印到终端。
I know the method is being called because "Model saved" is printed to the terminal.
是否有可能进入一个观察里面的闪光灯,如果是的话,怎么办?
Is it possible to access the flash inside an observer, and if so, how?
我需要设置闪光[:通知]
模型覆盖了通用的@model是successfuly更新。
I needed to set flash[:notice]
in the model to override the generic "@model was successfuly updated".
这就是我所做的。
创建名为各自的模型中的虚拟属性 flash_notice
然后,我需要的时候将相应的模型中的虚拟属性
在使用的after_filter当这个虚拟属性不是空白,以覆盖默认的Flash
您可以看到我的控制器和模型我如何做到了这一点如下:
You can see my controller and model how I accomplished this below:
class Reservation < ActiveRecord::Base
belongs_to :retailer
belongs_to :sharedorder
accepts_nested_attributes_for :sharedorder
accepts_nested_attributes_for :retailer
attr_accessor :validation_code, :flash_notice
validate :first_reservation, :if => :new_record_and_unvalidated
def new_record_and_unvalidated
if !self.new_record? && !self.retailer.validated?
true
else
false
end
end
def first_reservation
if self.validation_code != "test" || self.validation_code.blank?
errors.add_to_base("Validation code was incorrect")
else
self.retailer.update_attribute(:validated, true)
self.flash_notice = "Your validation as successful and you will not need to do that again"
end
end
end
class ReservationsController < ApplicationController
before_filter :authenticate_retailer!
after_filter :flash_notice, :except => :index
def flash_notice
if !@reservation.flash_notice.blank?
flash[:notice] = @reservation.flash_notice
end
end