在Rails

时间:2016-01-17 17:13:30

标签: ruby-on-rails ruby forms

我继承了一个静态网站,主页上有一个典型的联系表格,上面有姓名,电子邮件,电话和短信,并且应该在提交时发送电子邮件到设定的电子邮件地址。下面的JS和Slim部分给了我。我现在正在尝试使用ActionMailer连接到Rails,但我在使用表单参数和/或构建电子邮件对象时遇到了问题。我不打算将它存储在数据库中(使用和不使用模型进行尝试)。

路线: resources :contacts, only: [:new, :create]

_contact_form.slim

(我所有改变的是action值)

form#contactform.form-horizontal action="/contacts" method="post" name="contactform" role="form"
        /! Field 1
        .row
          .col-md-6
            h3 name:
            .input-text.form-group.left-field
              input.input-name.form-control name="contact_name" type="text" /
          .col-md-6
            h3 Phone:
            .input-text.form-group
              input.input-name.form-control name="contact_phone" type="text" /
        /! Field 2
        h3 Email:
        .input-email.form-group
          input.input-email.form-control name="contact_email" type="email" /
        /! Field 3
        h3 Message:
        .textarea-message.form-group
          textarea.textarea-message.form-control name="contact_message" rows="7"
        /! Button
        button.btn.btn-default type="submit"
          | Submit
          i.flaticon-arrow209

使用Javascript:

(我已设置url并添加了beforeSend

  /* --------------------------------------------
Contact Form
-------------------------------------------- */
$(function($) {
    $('#contactform').bootstrapValidator({
        message: '',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            contact_name: {
                validators: {
                    notEmpty: {
                        message: ''
                    }
                }
            },
            contact_email: {
                validators: {
                    notEmpty: {
                        message: ''
                    },
                    emailAddress: {
                        message: ''
                    }
                }
            },
            contact_message: {
                validators: {
                    notEmpty: {
                        message: ''
                    }
                }
            }
        },
        submitHandler: function(validator, form, submitButton) {
            $('.contact-form').addClass('ajax-loader');
            var data = $('#contactform').serialize();
            $.ajax({
                type: "POST",
                url: "/contacts",
                beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
                data: $('#contactform').serialize(),
                success: function(msg) {
                    $('.contact-form').removeClass('ajax-loader');
                    $('.form-message').html(msg);
                    $('.form-message').show();
                    submitButton.removeAttr("disabled");
                    resetForm($('#contactform'));
                },
                error: function(msg) {
                    $('.contact-form').removeClass('ajax-loader');
                    $('.form-message').html(msg);
                    $('.form-message').show();
                    submitButton.removeAttr("disabled");
                    resetForm($('#contactform'));
                }
            });
            return false;
        },
    });
    function resetForm($form) {
        $form.find('input:text, input:password, input, input:file, select, textarea').val('');
        $form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
    }
});

contact.rb

class Contact

  include ActiveModel::Model
  include ActiveModel::Conversion
  include ActiveModel::Validations

  attr_accessor :contact_name, :contact_phone, :contact_email, :contact_message

  validates :contact_name, :contact_email, :contact_message, presence: true

end

contacts_controller.rb:

class ContactsController < ApplicationController

  def create
    @contact = Contact.new(contact_params)

    if @contact.valid?
      ContactMailer.contact_email(@contact).deliver
      redirect_to new_contact_path, notice: "Thank you for your message."
    else
      flash[:alert] = "An error occurred while delivering this message."
      render :new
    end
  end

private

  def contact_params
    params.require(:contact).permit(:contact_name, :contact_phone, :contact_email, :contact_message)
  end

end

contact_mailer.rb

class ContactMailer < ActionMailer::Base

  default to: "me@myemailaddress.com"

  def contact_email(contact)
    @contact = contact

    mail(from: email: @contact.contact_email, body: @contact.contact_message)
  end

end

contact_email.text.slim

| New contact

= @contact.contact_name 
= @contact.contact_email 
| wrote:

= @contact.contact_message

Rails服务器的当前输出 Rails Server

我目前在contact_mailer.rb对象的@contact中收到语法错误,但在此之前,Rails服务器日志告诉我Contact对象未初始化。我尝试过包含form_for / form_tag Rails助手,但这似乎没有帮助。我还在HomeController添加了联系人的索引操作,并在其他地方阅读了此建议。

我可以继续播放'更改错误信息'但我想我得到了一些根本错误(仍然是Rails新手)所以非常感谢任何指针。我已经阅读了ActionMailer文档以及我能找到的所有其他内容。

1 个答案:

答案 0 :(得分:0)

你的contact_mailer.rb电话之后,你需要有.deliver吗?

另外,在您的contact.rb中尝试添加

after_create :send_email

private 
def send_email
    ContactMailer.contact_email(self).deliver
end