在模型中访问 rails flash[:notice] [英] Accessing rails flash[:notice] in a model
问题描述
我正在尝试将消息分配给模型观察者中的 flash[:notice].
I am trying to assign a message to flash[:notice] in a model observer.
这个问题已经有人问过了:Ruby on Rails: Observers and flash[:notice] 消息?
This question has already been asked: Ruby on Rails: Observers and flash[:notice] messages?
但是,当我尝试在我的模型中访问它时收到以下错误消息:
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>
这是我的代码:
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.
是否可以访问观察者内部的 flash,如果可以,如何访问?
Is it possible to access the flash inside an observer, and if so, how?
推荐答案
我需要在模型中设置 flash[:notice]
以覆盖通用的@model was successfully updated".
I needed to set flash[:notice]
in the model to override the generic "@model was successfully updated".
这是我做的
- 在各自的模型中创建了一个名为
validation_message
的虚拟属性 - 然后我在需要时在各自的模型中设置虚拟属性
- 当此虚拟属性不为空时使用 after_action 来覆盖默认 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, :validation_messages
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.validation_message = "Your validation is successful and you will not need to do that again"
end
end
end
class ReservationsController < ApplicationController
before_filter :authenticate_retailer!
after_filter :validation_messages, :except => :index
def validation_messages
return unless @reservation.validation_message.present?
flash[:notice] = @reservation.validation_message
end
end
一种可能的重构是将实际消息移动到适当的文件(例如语言环境)中,并仅将适当的密钥传递给 validation_message
.
One possible refactor would be to move the actual message in a proper file (e.g. a locale) and pass to validation_message
only the proper key.
如果您需要多个通知,可以很容易地将 validation_message
转换为数组或散列并将其称为 validation_messages
.
Should you need more than one notice it's easy enough to turn validation_message
into an array or a hash and call it validation_messages
instead.
这篇关于在模型中访问 rails flash[:notice]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!