我正在尝试在我的应用程序的页脚中设置一个简单的联系表单。表单验证有效,但我没有收到电子邮件。
我遵循了本教程,但更改了一些内容,因为联系表单在页脚中,而不是messages/new.html.erb
在我的应用程序中不存在的页面中。
我的路由文件有以下内容:
post 'contact-me', to: 'messages#create', as: 'create_message'
这是消息模型(无迁移)、控制器和邮件程序:
# message.rb
class Message
include ActiveModel::Model
attr_accessor :name, :email, :body
validates :name, :email, :body, presence: true
end
# messages_controller.rb
class MessagesController < ApplicationController
def create
message_params = params.require(:message).permit(:name, :email, :body)
@message = Message.new message_params
if @message.valid?
MessageMailer.contact_me(@message).deliver_now
flash[:success] = "Message sent"
redirect_to :back
else
flash[:danger] = "Message not sent. Please fill in all fields."
redirect_to :back
end
end
end
# message_mailer.rb
class MessageMailer < ApplicationMailer
def contact_me(message)
@body = message.body
# Note: my actual email is here, I just omitted it for this question
mail to: "<my-email>", from: message.email
end
end
由于联系表单在视图的每一页上,我在 ApplicationController 中做了新的操作:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
include SessionsHelper
before_filter :get_message
def get_message
@message = Message.new
end
end
_footer.html.erb 部分呈现联系表单:
# shared/_contact_form.html.erb
<%= form_for @message, url: create_message_url do |f| %>
<%= notice %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_field :name, placeholder: 'name' %>
<%= f.email_field :email, placeholder: 'email' %>
<%= f.text_area :body, placeholder: 'body' %>
<%= f.submit 'Send' %>
<% end %>
在config/application.rb
文件中添加以下 smtp 设置:
config.action_mailer.default_url_options = { :host => 'http://www.xxxx.com' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:user_name => "[email protected]",
:password => "xxxxxxxx",
:authentication => "plain",
:enable_starttls_auto => true
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句