简体   繁体   English

Ruby on Rails:观察者和flash [:notice]消息吗?

[英]Ruby on Rails: Observers and flash[:notice] messages?

I'm trying send flash messages and welcome notices to users if it's their first time commenting; 我正在尝试向用户发送即时消息和欢迎通知,如果这是他们第一次发表评论; basically, something like this: 基本上是这样的:

  class CommentObserver < ActiveRecord::Observer
    def after_save(comment)
      if comment.user.new?
        Mailer.deliver_welcome_package(comment)
        flash[:notice] = "Welcome! We just delivered a welcome package to your email"
      end
    end
  end

I'm not sure how I should display that flash message for users after they create their first comment. 我不确定用户创建第一个评论后应如何向用户显示该即显消息。 Should I put that flash message in the controller (with an additional "if comment.user.new?") or is there a way to display the flash message more efficiently? 我应该将该Flash消息放入控制器中(是否带有附加的“ if comment.user.new?”),还是可以更有效地显示Flash消息?

Putting the flash message in the method seems fine to me. 对我来说,将Flash消息放入方法中似乎不错。

I usually have a helper method in my application_helper file that checks flash and diplays. 我的application_helper文件中通常有一个辅助方法,用于检查Flash和diplay。

def show_flash
    [:notice, :error, :warning].collect do |key|
      content_tag(:div, flash[key], :id => key, :class => "flash flash_#{key}") unless flash[key].blank?
    end.join
  end

I have three types of messages, notice, warning, and error, this checks to see if any of them are set, if so it prints them out, if not then nothing is printed. 我有三种消息,注意,警告和错误,它们检查是否设置了任何消息,如果设置了,则将其打印出来,如果未设置,则不打印任何内容。

In my layout i then have.. 在我的布局中,然后有..

<% show_flash %>

Firstly, why are you observing comments? 首先,为什么要观察评论? If you want to react to a new user, why don't you observe users? 如果您想对新用户做出反应,为什么不观察用户?

To answer your question, I would definitely put the flash assignment in your controller, the reason being that the flash is a view level concern. 要回答您的问题,我肯定会将闪存分配放在您的控制器中,原因是闪存是视图级别的关注点。

I used to use observers for sending mails, but have more recently just sent them in the controller. 我曾经使用观察者来发送邮件,但最近只是在控制器中发送了它们。 In this case, doing that would make your life a little simpler. 在这种情况下,这样做会使您的生活更加简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM