代码之家  ›  专栏  ›  技术社区  ›  titaniumdecoy Mr. T

访问模型中的rails flash[:notice]

  •  12
  • titaniumdecoy Mr. T  · 技术社区  · 15 年前

    我试图在模型观察者中为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

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

    有可能进入观察者内部的闪光灯吗?如果有,怎么做?

    2 回复  |  直到 7 年前
        1
  •  10
  •   sohaibbbhatti    7 年前

    我需要设置 flash[:notice] 在模型中重写泛型“@model was successfully updated”。

    我就是这么做的

    1. 在相应的模型中创建了一个名为 flash_notice
    2. 然后根据需要在相应的模型中设置虚拟属性
    3. 当此虚拟属性不为空时使用after_筛选器覆盖默认闪存

    你可以在下面看到我的控制器和模型,我是如何做到这一点的:

    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
    
        2
  •  20
  •   Ryan Bigg Andrés Bonilla    15 年前

    不,您在进行保存的控制器中设置它。 flash 是在 ActionController::Base .