tit*_*coy 12 activerecord ruby-on-rails rails-flash
我试图在模型观察者中为flash [:notice]分配一条消息.
这个问题已经被问到:Ruby on Rails:Observers和flash [:notice]消息?
但是,当我尝试在我的模型中访问它时,我收到以下错误消息:
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
endRun Code Online (Sandbox Code Playgroud)
我知道正在调用该方法,因为"模型保存"被打印到终端.
是否有可能在观察者内部访问闪存,如果是这样,怎么办?
Rya*_*igg 20
不,您将其设置在正在进行保存的控制器中.flash是一种定义的方法ActionController::Base.
the*_*gah 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17932 次 |
| 最近记录: |