使用rails 4,邮件表单和ajax发送电子邮件?

我正在开发一个有联系表格的应用程序。 它是一个单页应用程序,我在后端使用rails,并在前端使用angular(不是表单)和bootstrap。 我正在尝试使用ajax,所以我不必刷新页面。 当我让它使用rails(使用Mailform)提交时,它看起来像是在工作。

当我进入console并输入;

 c = Contact.new(:name => "name", :email => "email@email.com", :message => "hi") c.deliver 

在控制台,我得到;

 Rendered vendor/bundle/gems/mail_form-1.5.0/lib/mail_form/views/mail_form/contact.erb (2.9ms) MailForm::Notifier#contact: processed outbound mail in 29.2ms Sent mail to [EMAIL] (5.1ms) Date: Fri, 25 Jul 2014 14:52:20 -0700 From: Name  To: [EMAIL] Message-ID:  Subject: Onyx Contact Form Mime-Version: 1.0 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: 7bit 

Onyx Contact Form

Name: Name

Email: email@email.com

Message: Hi

=> true

这看起来很有效。 但是,我不确定是不是因为我没有收到我的电子邮件(但也许电子邮件不在本地发送?)。 当我尝试使用ajax提交并按“提交”时没有任何反应,所以我知道我的javascript是不对的。

这是我的其余代码;

index.html.erb

 
true, :hide_label => true, :placeholder => "Name" %> true, :hide_label => true, :placeholder => "Email" %> true, :hide_label => true, :plceholder => "Hello, we'd love to work with you" %>

contact.rb

 class Contact  true attribute :email, :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i attribute :message attribute :nickname, :captcha => true # Declare the e-mail headers. It accepts anything the mail method # in ActionMailer accepts. def headers { :subject => "Onyx Contact Form", :to => "[MY_EMAIL]", :from => %("#{name}" ) } end end 

contacts_controller.rb

 class ContactsController < ApplicationController def new @contact = Contact.new end def create @contact = Contact.new(params[:contact]) @contact.request = request if @contact.deliver flash[:notice] = 'Thank you for your message. We will contact you soon!' redirect_to root_url else flash.now[:error] = 'Cannot send message.' render :new end end end 

main.js

 $(function(){ $("#form").submit(function(){ var dataSet = $(this).serialize(); $.ajax({ type: "POST", url: $(this).attr("action"), data: dataSet, complete: function(){ alert("Sent!"); }, error: function(){ alert("Something went wrong!"); } }); return false; }); }) 

的routes.rb

 match '/contacts', to: 'contacts#new', via: 'post' resources :contacts, as: 'home' #home so it doesn't go to another page 

我还在其他SO答案中找到的配置文件中添加了一些东西,我不确定它是否正在做任何事情。 通常我不会使用ajax来提交表单,但因为它是单页,所以不能选择路由到另一个页面。 如果使用邮件forms太难,可能Action Mailer是更好的选择吗? 任何指示我正确方向的帮助将不胜感激。

第一步,将config.action_mailer.perform_deliveries = true添加到config/environments/development.rb

有了它,您可以在开发模式下发送电子邮件。

第二步rails 4使用strong parameters ,这意味着您需要将参数列入时间,以便在控制器中添加以下方法:

 def contacts_params params.require(:contact).permit(:name, :email, :message) end 

然后使用@contact = Contact.new(contacts_params)更改此行@contact = Contact.new(params[:contact]) @contact = Contact.new(contacts_params)

请尝试这些更改。

编辑:

在您的路线中,您要拨打“contacts#new”而不是“contacts#create”,这样就无法访问您的代码。

此外,如果您不需要remote: true因为您手动处理提交内容