在模型中访问rails flash
我试图在模型观察者中为flash [:notice]分配一条消息。
这个问题已经被问到: Ruby on Rails:Observers和flash [:notice]消息?
但是,当我尝试在我的模型中访问它时,我收到以下错误消息:
未定义的局部变量或方法`flash'用于#
这是我的代码:
class ModelObserver < ActiveRecord::Observer observe A, B, C def after_save(model) puts "Model saved" flash[:notice] = "Model saved" end end
我知道正在调用该方法,因为“模型保存”被打印到终端。
是否有可能在观察者中访问闪存,如果是这样,如何?
我需要在模型中设置flash[:notice]
来覆盖generics“@model was successfuly updated”。
这就是我做的
- 在相应的模型中创建了一个名为
flash_notice
的虚拟属性 - 然后我在需要时在相应的模型中设置虚拟属性
- 当此虚拟属性不为空时使用after_filter来覆盖默认闪存
你可以看到我的控制器和模型,我在下面完成了这个:
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 end
不,您将其设置在正在进行保存的控制器中。 flash
是ActionController::Base
上定义的方法。