ruby-on-rails Rails after_保存回调创建“堆栈级别太深”循环

ehxuflar  于 6个月前  发布在  Ruby
关注(0)|答案(1)|浏览(84)

我有一个设置,其中Chapter s通过has_manyQueueItem s关系放置在队列中。一个Chapter可以有许多QueueItem s,因为在QueueItem被标记为approved(这是一个布尔值)之前,它可能必须经历几次修订过程。
每个QueueItem都有一个position,它只是一个整数,用来指示它在行中的位置。我试图在chapter.rbqueue_item.rb模型中创建一个方法,当一个项目被批准时,它可以重新排序队列。
方法(目前在queue_item.rb内部)看起来像这样:

def reorder_queue
    Chapter.where(should_be_queued: true).order("created_at ASC").each_with_index do | chapter, index |
      chapter.most_recent_queue_item.update(position: index + 1)
    end
  end

字符串
它引用了chapter.most_recent_queue_itemchapter.rb方法,就是这样:

def most_recent_queue_item
    item = QueueItem.where(chapter_id: self.id).last
    item
end


我遇到的问题是,当QueueItem被更新时,我需要reorder_queue方法为after_save.
有没有人知道我应该如何构造这个,这样我就不会陷入无限循环了?我觉得这应该是一个很常见的问题。

jxct1oxe

jxct1oxe1#

你必须跳过回调,这样代码就不会进入无限循环,因为回调在_保存回调之后调用更新和更新触发器

相关问题