我正在尝试使用 Rails 4.2 的 Deliver_later 方法设置联系表格。但是,我只能让 Deliver_now 工作,因为 Deliver_later 试图序列化我的对象并且每次都失败。
这是我的设置:
消息控制器.rb
class MessagesController < ApplicationController
def new
@message = Message.new
end
def create
@message = Message.new(params[:message])
if @message.valid?
ContactMailer.contact_form(@message).deliver_later
redirect_to root_path, notice: "Message sent! Thank you for contacting us."
else
render :new
end
end
end
contact_mailer.rb
class ContactMailer < ApplicationMailer
default :to => Rails.application.secrets['email']
def contact_form(msg)
@message = msg
mail(:subject => msg.subject, from: msg.email)
end
end
消息.rb
class Message
include ActiveModel::Model
include ActiveModel::Conversion
## Not sure if this is needed ##
include ActiveModel::Serialization
extend ActiveModel::Naming
attr_accessor :name, :subject, :email, :body
validates_presence_of :email, :body
validates_format_of :email, with: /\A([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})\z/i
validates_length_of :body, :maximum => 1000
def initialize(attributes = {})
attributes.each { |name, value| send("#{name}=", value) }
end
## Not sure if this is needed ##
def attribtues
{'name' => nil, 'subject' => nil, 'email' => nil, 'body' => nil}
end
end
我打电话时遇到的错误ContactMailer.contact_form(@message).deliver_later
是:
ActiveJob::SerializationError in MessagesController#create
Unsupported argument type: Message
Extracted source (around line #10):
if @message.valid?
ContactMailer.contact_form(@message).deliver_later
redirect_to root_path, notice: "Message sent! Thank you for contacting us."
else
render :new
理想情况下,我希望这是一个后台进程。我很快就会添加类似 Sidekiq 的东西,但我认为最好事先解决这个序列化问题。
任何帮助表示赞赏!谢谢 :)