2010-04-23 53 views
12

我试图在模型观察者中为flash [:notice]指定一条消息。在模型中访问rails 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

我知道该方法被调用,因为“模型保存”被打印到终端。

是否有可能访问观察者内部的闪光灯,如果是这样,如何?

+1

打破MVC技术上有效的解决方案:http://stackoverflow.com/questions/393395/how-to-call-expire-fragment-from-rails-observer-model/608700#608700 – titaniumdecoy 2012-06-16 06:27:07

回答

11

我需要在模型中设置flash[:notice]以覆盖泛型“@model was successfuly updated”。

这就是我所做的

  1. 创建名为flash_notice
  2. 然后我设置在相应的模型中的虚拟属性需要时各自的模型虚拟属性
  3. 使用的after_filter当这个虚拟属性是不空白,以覆盖默认的Flash

你可以看到我的控制器和模型我如何完成这个如下:

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 [email protected]_notice.blank? 
     flash[:notice] = @reservation.flash_notice 
    end 
    end 
end 
+0

你简化你的'if'条件到'@ reservation.flash_notice.present?'而不是''不是空白? – Besi 2016-03-14 23:18:13

17

不,您将其设置在正在进行保存的控制器中。 flash是在ActionController::Base上定义的方法。

+6

瑞安的权利,虽然。您应该在控制器中设置闪光灯......这是视图表示层的功能。上面的“答案”是很多危险的重要工作来完成这项工作。 – 2010-04-24 03:50:22

+0

正如我在我的文章中所说的,在我的应用程序中将控制器中的闪光灯设置为不切实际(如果甚至可能的话)。每次模型更新时,我都需要向闪光灯添加消息;我不知道另一种方法 - 至少不会在墙上扔一盘意大利面代码。 – titaniumdecoy 2010-04-24 06:44:31

+0

我今天简单地扼杀了这个,但是在解决了我自己的困境之后,我发现你在上面的评论中回答了你的问题。 “每次模型更新时,我都需要向闪光灯添加一条消息。”我知道你说这是不切实际的,但我把我的闪光灯放在我的控制器的更新方法中。 (捕捉一个异常,然后闪烁一个错误。) – Tass 2012-06-01 21:34:38

相关问题