在模型中访问Rails Flash [:注意
-
01-10-2019 - |
题
我正在尝试将消息分配给模型观察者中的flash [:注意]。
这个问题已经被问到: Ruby on Rails:观察者和Flash [:注意]消息?
但是,当我尝试在模型中访问它时,我会收到以下错误消息:
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
我知道该方法之所以被称为,是因为“保存模型”已打印到终端。
是否可以访问观察者内部的闪光灯,如果是,如何?
解决方案
我需要设置 flash[:notice]
在覆盖通用“ @model成功更新”的模型中。
这是我所做的
- 在相应的模型中创建了一个虚拟属性
flash_notice
- 然后,我在需要时在相应模型中设置虚拟属性
- 当此虚拟属性不是空白以覆盖默认闪存时,使用after_filter
您可以看到我的控制器并建模我如何完成此操作:
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
其他提示
不,您将其设置在保存发生的控制器中。 flash
是定义的方法 ActionController::Base
.
不隶属于 StackOverflow