rails 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>
routes.rb
resources :contact, only: [:create]
contact.rb
class Contact < MailForm::Base
attribute :name, validate: true
attribute :email, validate: true
attribute :message
def headers
{
subject: "My Contact Form",
to: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="620f1b070f030b0e22050f030b0e4c010d0f" rel="noreferrer noopener nofollow">[email protected]</a>',
from: %("#{name}" <#{email}>)
}
end
end
contact_controller.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
我做错了什么或者我错过了什么步骤?
编辑 Controller
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>
编辑的routes.rb
resources :contacts, only: [:create]
最佳答案
resources :contacts, only: [:create]
资源应该是复数。
class ContactsController < ApplicationController
def create
@contact = Contact.new(contact_params)
if @contact.deliver
# You can't both render and redirect
render json: { message: "Email sent successfully" }
else
render json: @contact.errors
end
end
private
def contact_params
params.require(:contact)
.permit(:name, :email, :message)
end
end
参数嵌套在 params[:contact][:name]
、params[:contact][:email]
等中。使用 strong parameters将批量分配的参数列入白名单,而不是充当人工编译器。
关于ruby-on-rails - Rails ActionController::RoutingError (没有路由匹配 [POST] "/"):,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67199249/