我正在尝试在模型观察者中为flash [:notice]分配一条消息。
此问题已被提出:Ruby on Rails: Observers and flash[:notice] messages?
但是,当我尝试在我的模型中访问它时,收到以下错误消息:
undefined local variable or method `flash' for #<ModelObserver:0x2c1742c>
这是我的代码:
class ModelObserver < ActiveRecord::Observer
observe A, B, C
def after_save(model)
puts "Model saved"
flash[:notice] = "Model saved"
end
end
我知道正在调用该方法,因为“已保存模型”将打印到终端。
是否可以在观察者中访问闪存,如果可以,如何访问?
答案 0 :(得分:20)
不,您将其设置在正在进行保存的控制器中。 flash
是ActionController::Base
上定义的方法。
答案 1 :(得分:10)
我需要在模型中设置flash[:notice]
以覆盖通用“@model已成功更新”。
这就是我所做的
flash_notice
您可以在下面看到我的控制器和模型,如何完成此操作:
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