ruby-on-rails – Rails 4.2:使用无桌面模型的deliver_later

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails 4.2:使用无桌面模型的deliver_later前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用Rails 4.2的deliver_later方法设置联系表单.但是,我只能让deliver_now工作,因为deliver_later正在尝试序列化我的对象,每次都失败.

这是我的设置:

messages_controller.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

message.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这样的东西,但我认为这是最好的事先修复这个序列化问题.

任何帮助是赞赏!谢谢 :)

解决方法

为了使用ActiveJob(这是delivery_later委托给你的)类,它需要能够通过其ID来唯一地标识该对象.此外,需要在反序列化时通过ID找到它(邮件/作业中不需要手动反序列化).
class Message
  ...
  include GlobalID::Identification
  ...

  def id
    ...
  end

  def self.find(id)
    ...
  end
end

ActiveRecord将为您提供这些方法,但由于您没有使用它,您需要自己实现.决定您要存储记录的位置由您决定,但老实说,我认为通过使用ActiveRecord和下表可以更好地使用.

原文链接:https://www.f2er.com/ruby/273146.html

猜你在找的Ruby相关文章