我想用 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: undefined method `primary_key' for Hash:Class
使用此方法创建的对象(在本例中为事件):
Track(:shift_created_event, {eventable: @shift, creator: current_user})
Track方法如下所示:
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)
有人有这方面的经验吗?