导轨 6.0.3
我已经使用gem 'mail_form'
.
我知道它工作正常,因为我可以从 rails 控制台发送电子邮件。
问题出在表单上,当我按下提交时,它会出现路由错误。
ActionController::RoutingError (No route matches [POST] "/"):
主页表格
<div class="container">
<%= form_with model: @contact do |f| %>
<div class="mb-3">
<h3><%= f.label :name, class: "label" %></h3>
<%= f.text_field :name, class: "form-control", placeholder: "Write name in here" %>
<%= f.text_field :email, class: "form-control", placeholder: "Write email in here" %>
<%= f.text_field :message, class: "form-control", placeholder: "Write message in here" %>
<%= f.submit %>
</div>
<% end %>
</div>
路线.rb
resources :contact, only: [:create]
联系人.rb
class Contact < MailForm::Base
attribute :name, validate: true
attribute :email, validate: true
attribute :message
def headers
{
subject: "My Contact Form",
to: 'myemail@gmail.com',
from: %("#{name}" <#{email}>)
}
end
end
联系人控制器.rb
class ContactController < ApplicationController
def create
@contact = Contact.new()
@contact.name = params[:name]
@contact.email = params[:email]
@contact.message = params[:message]
if @contact.deliver
render json: {message: "Email sent successfully"}
redirect_to root_path
else
render json: @contact.errors
end
end
end
我做错了什么或错过了什么步骤?
编辑控制器
class ContactController < ApplicationController
def create
@contact = Contact.new(contact_params)
if @contact.deliver
redirect_to root_path
else
render json: @contact.errors
end
end
private
def contact_params
params.require(:contact).permit(:name, :email, :message)
end
end
编辑过的表格
<div class="container">
<%= form_for Contact.new, url: contacts_path do |f| %>
<div class="mb-3">
<h3><%= f.label :name, class: "label" %></h3>
<%= f.text_field :name, class: "form-control", placeholder: "Write name in here" %>
<%= f.text_field :email, class: "form-control", placeholder: "Write email in here" %>
<%= f.text_field :message, class: "form-control", placeholder: "Write message in here" %>
<%= f.submit %>
</div>
<% end %>
</div>
编辑路线.rb
resources :contacts, only: [:create]