【问题标题】:stack level too deep after_save callback in Rails4Rails4中的堆栈级别太深after_save回调
【发布时间】:2013-12-17 12:31:17
【问题描述】:

我的模型是这样的,

class Slot
  include Mongoid::Document
  after_save :calculate_period

  field :slot, type: Array

  def calculate_period
    if condition
     do something
    end
  self.slot = true
  save
  end

end

提交按钮后会显示这个错误, SlotsController#create 中的 SystemStackError 堆栈级别太深

而且还花费更多时间。如果我从 def calculate_period 中删除保存,则这些值不会存储 after_save 回调。

任何解决方案...!!!

【问题讨论】:

  • 你在保存后保存:无限循环

标签: ruby-on-rails mongodb mongoid


【解决方案1】:

你应该把它改成before_save,这样你就可以改变模型的属性,然后它们会像往常一样保存到数据库中。

class Slot
  include Mongoid::Document
  before_save :calculate_period

  def calculate_period
    if condition
      #do something
    end
  end

end

【讨论】:

    【解决方案2】:

    您有无限循环 - 在 calculate_period 方法中调用 save 会调用回调,包括您的 calculate_period 回调。我想到的第一个解决方案是添加虚拟属性并在调用回调方法之前对其进行检查:

    class Slot
      include Mongoid::Document
      after_save :calculate_period, unless: :period_calculated # I'm not sure if Mongoid allows this
      attr_accessor :period_calculated
    
      def calculate_period
        if condition
          # do something
        end
        self.period_calculated = true
        save
      end
    end
    

    【讨论】:

    • 像你一样,但在数组属性中给出错误,问题:TrueClass 类型的值无法写入数组类型的字段摘要:试图将 TrueClass 类型的值设置为数组类型的字段解决方法:验证要设置的值是否对应字段定义
    • 听起来有些东西与 'attr_accessor' 的意思很矛盾。一些巨大的宝石链可能需要一些宝石。如果您可以编写 5 行代码而不是使用需要其他 gem 的 gem,那么从长远来看,您会更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 2013-10-05
    • 2011-11-17
    • 2012-07-24
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多