2010-04-23 56 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

相關問題