简体   繁体   中英

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?

Putting the flash message in the method seems fine to me.

I usually have a helper method in my application_helper file that checks flash and diplays.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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