我有一个简单的工作器,它对某些文本执行方法并将它们存储在变量中。如何将这些数据保存到已分配的列中?
控制器:
def create
@blog = Blog.new(blog_params)
if @blog.save
Resque.enqueue(Counter, Blog.extract_text)
redirect_to backend_blogs_path, notice: "Success!"
else
render "new"
end
end
型号:
def self.extract_text
Blog.last.text
end
工人:
class Counter
@queue = :count
def self.perform(*args)
@wordcount = args.count
@@charactercount = args.size
@whitespacecount = args.count(" ")
end
end
如您所见,我需要将这三个变量中的数据存储到数据库的列中。
create_table "blogs", force: :cascade do |t|
t.string "title"
t.string "text"
t.string "image"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug"
t.boolean "active"
t.integer "whitespacecount"
t.integer "charactercount"
t.integer "wordcount"
t.index ["slug"], name: "index_blogs_on_slug", unique: true
end
我是否需要将它们传回控制器?
答案 0 :(得分:0)
不是直接将文本传递给工作人员,而是传递博客的ID:
# in your controller
def create
@blog = Blog.new(blog_params)
if @blog.save
Resque.enqueue(Counter, @blog.id)
redirect_to backend_blogs_path, notice: "Success!"
else
render "new"
end
end
然后在你的工作人员中,加载博客,分析它并写回数据库:
# in the worker
class Counter
@queue = :count
def self.perform(blog_id)
blog = Blog.find(blog_id)
blog.update(
wordcount: blog.text.split(' ').count,
charactercount: blog.text.size,
whitespacecount: blog.text.count(' ')
)
end
end