访问钢轨闪光[:声明]在一个模型 [英] Accessing rails flash[:notice] in a model

查看:117
本文介绍了访问钢轨闪光[:声明]在一个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想分配一个消息闪烁[:通知],在模型观察

I am trying to assign a message to flash[:notice] in a model observer.

这个问题已经被问:<一href="http://stackoverflow.com/questions/2001199/ruby-on-rails-observers-and-flashnotice-messages">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".

这就是我所做的。

  1. 创建名为各自的模型中的虚拟属性 flash_notice
  2. 然后,我需要的时候将相应的模型中的虚拟属性
  3. 在使用的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 

这篇关于访问钢轨闪光[:声明]在一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆