加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails /延迟作业:无法在延迟作业中保存模型

发布时间:2020-12-17 02:01:31 所属栏目:百科 来源:网络整理
导读:我有一个Post模型(下面),它有一个回调方法来通过延迟作业修改body属性.如果我删除“延迟”.然后执行#shorten_urls!瞬间,它工作正常.但是,从延迟作业的上下文来看,它不会保存更新的正文. class Post ActiveRecord::Base after_create :shorten_urls def shor
我有一个Post模型(下面),它有一个回调方法来通过延迟作业修改body属性.如果我删除“延迟”.然后执行#shorten_urls!瞬间,它工作正常.但是,从延迟作业的上下文来看,它不会保存更新的正文.

class Post < ActiveRecord::Base
  after_create :shorten_urls

  def shorten_urls
    delay.shorten_urls!
  end

  def shorten_urls!
    # this task might take a long time,# but for this example i'll just change the body to something else
    self.body = 'updated body'
    save!
  end
end

奇怪的是,处理工作没有任何问题:

[Worker(host:dereks-imac.home pid:76666)] Post#shorten_urls! completed after 0.0021
[Worker(host:dereks-imac.home pid:76666)] 1 jobs processed at 161.7611 j/s,0 failed ...

然而,身体没有更新.谁知道我做错了什么?

– 编辑 –

根据Alex的建议,我已将代码更新为这样(但无济于事):

class Post < ActiveRecord::Base
  after_create :shorten_urls

  def self.shorten_urls!(post_id=nil)
    post = Post.find(post_id)
    post.body = 'it worked'
    post.save!
  end

  def shorten_urls
    Post.delay.shorten_urls!(self.id)
  end
end

解决方法

其中一个原因可能是当您将方法传递给延迟时,self未正确序列化.尝试制作shorten_urls!一个类方法,它接受记录id并从DB中获取它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读