您如何 运行 仅在用户被重定向后才在控制器中发送邮件?

How do you run a mailer only after a user has been redirected, in a controller?

比如邮件程序send_signup_mail很重,需要一段时间才能完成,如何让sign_in_and_redirect先执行,视图渲染后在后台发送邮件。

在下面的代码中,这只需要按线性顺序执行,但我认为这不是实际发生的事情,因为重定向在邮件发送后才完成。

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

    def facebook
        # You need to implement the method below in your model (e.g. app/models/user.rb)
        @fb_response = request.env["omniauth.auth"]
        @user = User.from_omniauth(@fb_response)

        if @user.persisted?
          # Update user token
          @user.fb_token = @fb_response.credentials.token
          # Sign in
          sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
          set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
          # Deliver signup mail
          UserNotifier.send_signup_email(@user).deliver
        else
          session["devise.facebook_data"] = request.env["omniauth.auth"]
          redirect_to new_user_registration_url
        end
    end

end

谢谢!

您应该使用后台作业来发送邮件,这样才不会影响用户体验。我建议你看看这个 gem:

Delayed Job

一旦你正确地配置了这个gem,你只需要使用

UserNotifier.delay.send_signup_email(@user)

让您的电子邮件在后台发送。