我在rails中设置了邮件程序,除了应该传递的实际邮件之外,一切正常。我正在尝试从发送的电子邮件中的数据库中呈现数据。我一直没有遇到方法错误。这就是我所拥有的:
contact_recieved.html.erb
<td valign="top">
<h2 style="color: #0f060f; font-size: 22px; text-align: center;"><%=@contact.subject%></h2>
<p style="color: #0f060f; font-size: 14px; line-height: 22px; text-align: center;">Name: <%=@contact.name%></p>
<p style="color: #0f060f; font-size: 14px; line-height: 22px; text-align: center;">Email: <%=@contact.email%></p>
<p style="color: #0f060f; font-size: 14px; line-height: 22px; text-align: center;">Message: <%=@contact.message%></p>
</td>
这是我的contact_controller.rb:
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def show
@contact = Contact.find(params[:id])
end
def create
# fail
@contact = Contact.create(contact_params)
if @contact.save
ContactMailer.contact_received(@contact).deliver
redirect_back(fallback_location: root_path)
else
flash[:error] = @contact.errors.full_messages
redirect_back(fallback_location: root_path)
end
end
private
def contact_params
params.require(:contact).permit(:name, :subject, :email, :message)
end
end
最后这是我的contact.rb模型:
class Contact < ApplicationRecord
email_regex = /\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :subject, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => {:with => email_regex }
validates :message, :presence => true,
:length => { :maximum => 5000 }
end
当我提交表单时,我一直收到无方法错误,请参阅下图:
当我提交数据时,数据将存储在数据库中,如下所示:
这是contact_mailer.rb
class ContactMailer < ApplicationMailer
default from: "info@***********"
def contact_received(contact)
mail(to: "*******.com", subject: "This is just a test from Jay")
end
end
更新
我将@contacts更改为@contact,我仍然收到相同的错误消息:
答案 0 :(得分:1)
更新您的邮件程序类以分配变量(@contact = contact
)。
class ContactMailer < ApplicationMailer
default from: "info@***********"
def contact_received(contact)
@contact = contact
mail(to: "*******.com", subject: "This is just a test from Jay")
end
end