如何首先渲染视图并使用Ruby on Rails和ActionMailer在后台发送电子邮件

时间:2012-06-19 00:15:03

标签: ruby-on-rails ajax actionmailer

我的应用有一个简单的注册,用户输入他/她的电子邮件地址并发送请求。然后使用AJAX将请求发送到我的服务器,使用ActionMailer将电子邮件发送到用户的电子邮件,并使用jQuery呈现感谢消息。使用我目前的代码,感谢信息仅在电子邮件发送后呈现,因此感谢消息显示需要一些时间。但是,我希望首先呈现感谢信息,并在后台发送给用户的电子邮件,以便用户可以立即知道他/她的电子邮件已保存。有没有办法用Rails在后台处理电子邮件?

以下是我目前的代码。 在users_controller.rb

def create
  @user = User.new(params[:user])

  respond_to do |format|
    if @user.save
      format.html { redirect_to @user, notice: 'Thank you for signing up!' }
      format.js
      format.json { render json: @user, status: :created, location: @user }
      Notifier.email_saved(@user).deliver
    else
      format.html { render action: "new" }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

在mailers / notifier.rb

class Notifier < ActionMailer::Base
  default from: "First Last <my@email.com>"

  def email_saved(user)
    @email = user.email
    mail to: @email, subject: 'Auto-Response: Thank you for signing up'
  end
end

在users / create.js.erb

$("<div class='alert alert-success'>Thank you for showing your interest! A confirmation email will be sent to you shortly.</div>").insertAfter("#notice");

谢谢!

1 个答案:

答案 0 :(得分:2)

如果您只想发送邮件,则应使用比“Ajax”更好的“Resque”或“Delayed Job”。

#271 Resque - RailsCasts http://railscasts.com/episodes/271-resque

Delayed Job (DJ) | Heroku Dev Center https://devcenter.heroku.com/articles/delayed-job

但是如果你想使用Ajax发送邮件,请使用下面的代码作为参考。

#app/controllers/users_controller.rb
def create
  @user = User.new(params[:user])

  respond_to do |format|
    if @user.save
      format.html { redirect_to @user, notice: 'Thank you for signing up!', sign_up_flag: 1 }
      format.js
      format.json { render json: @user, status: :created, location: @user }
    else
      format.html { render action: "new" }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

def send_mail(user_id)
    begin
      user = User.find(user_id)
      Notifier.sign_up_mail(user.email).deliver
      render :nothing => true, :status => 200
    rescue
      render :nothing => true, :status => 500
    end
end



#app/mailers/notifier.rb
class Notifier < ActionMailer::Base
  default from: "First Last <my@email.com>"

  def sign_up_mail(email)
    mail to: email, subject: 'Auto-Response: Thank you for signing up'
  end
end



#app/views/???.html.erb
<% if @sign_up_flag == 1 %>
  $(document).ready(function(){
    $.ajax({
      type: "POST",
      url:  "/sendmail",
      data: "",
      success : function(){},
      error : function() {}
    });
  });
<% end %>



#config/routes.rb
  post '/sendmail' => 'users#send_mail'

感谢。