使用sidekiq创建活动记录对象

时间:2013-02-20 16:05:29

标签: ruby ruby-on-rails-3 redis sidekiq

我想用sidekiq创建活动记录对象。我知道这不是最佳实践,因为我必须序列化整个对象,但在这种情况下没有其他选择。

如果我尝试一下,我得到:

  EventTrackingWorker JID-ec2be02dae626dd19202b17f INFO: start
  EventTrackingWorker JID-ec2be02dae626dd19202b17f INFO: fail: 0.033 sec
  WARN: {"retry"=>false, "queue"=>"default", "class"=>"EventTrackingWorker", "args"=>["shift_created_event", {... long json object ..}}, "create"], "jid"=>"ec2be02dae626dd19202b17f"}
  WARN: undefined method `primary_key' for Hash:Class
  WARN: /Users/jedi/.rbenv/versions/1.9.3-p194-perf/lib/ruby/gems/1.9.1/gems/activerecord-3.2.11/lib/active_record/reflection.rb:366:in `primary_key'
  /Users/jedi/.rbenv/versions/1.9.3-p194-perf/lib/ruby/gems/1.9.1/gems/activerecord-3.2.11/lib/active_record/reflection.rb:216:in `association_primary_key'

错误说明: WARN:哈希的未定义方法`primary_key':Class

使用此方法创建的对象(在本例中为事件):

Track(:shift_created_event, {eventable: @shift, creator: current_user})

跟踪方法如下所示:

module EventTracking
  module_function

  def Track(event, options, method=:create)
    EventTrackingWorker.perform_async(event, options, method)
  end

end

EventTrackingWorker班级:

class EventTrackingWorker
  include Sidekiq::Worker

  def perform(event, options, method=:create)
    event.to_s.classify.constantize.new(options).send(method)
  end

end

注意:event.to_s.classify.constantize.new(options).send(method)将字符串shift_created_event转换为有效记录类ShiftCreatedEvent,并使用选项调用new。之后我用.send(method)

创建对象

有人有经验吗?

0 个答案:

没有答案