代码之家  ›  专栏  ›  技术社区  ›  Eduardo León

检查记录是否刚刚在铁轨上被销毁

  •  97
  • Eduardo León  · 技术社区  · 17 年前

    record.new_record?
    

    检查是否有新的东西

    record = some_magic
    record.destroy
    record.is_destroyed? # => true
    

    7 回复  |  直到 17 年前
        1
  •  230
  •   Voldy    13 年前

    record.destroyed?
    

    详情请点击此处 ActiveRecord::Persistence

        2
  •  60
  •   Dan Andreasson ryanb    5 年前

    你可以做到这一点。

    Record.exists?(record.id)
    

    attr_accessor :destroyed
    after_destroy :mark_as_destroyed
    def mark_as_destroyed
      self.destroyed = true
    end
    

    然后检查 record.destroyed .

        3
  •  11
  •   Steve Klabnik    17 年前

    这很快就会到来。在最近的…… Riding Rails 帖子中写道:

    只有当实例 您当前查看的是 成功销毁。

        4
  •  6
  •   theIV    17 年前

    destroy 调用对象只返回对以下对象的调用 freeze frozen? 这是你最好的选择。你的另一个选择是从 ActiveRecord::RecordNotFound record.reload .

        5
  •  6
  •   Mischa    11 年前

    record = Object.find(params[:id])
    if record.destroy
      ... happy path
    else
      ... sad path
    end
    

        6
  •  1
  •   Mike Buckbee    17 年前

    如果不了解你的应用程序的更多逻辑,我认为它会冻结吗?这是你最好的选择。

        7
  •  0
  •   Ryan Taylor    3 年前

      record.destroyed? # doesn't always work (see below)
      # or...
      Record.exists?(record.id) # very fast!
    

    record.destroyed? 更好,因为它不会发送额外的数据库请求,但实际上 Record.exists? 如此极端

    record.destroy ,这将 https://apidock.com/rails/v5.2.3/ActiveRecord/Persistence/destroy

    # Assuming no issues when destroying the record...
    x = record_one.destroy
    x.destroyed? # Would return false! (even though the record no longer exists in the db)
    Record.exists?(x) # Would correctly return false
    # vs.
    record_two.destroy
    record_two.destroyed? # Would correctly return true
    Record.exists?(record_two) # Would correctly return false
    

    destroy! 会扔一个 ActiveRecord::RecordNotDestroyed before_destroy

    def destroy
      render json: @record.destroy!
    rescue ActiveRecord::RecordNotDestroyed
      # @record will work fine down here, it still exists.
      render json: { errors: ["Record not destroyed"] }
    end
    
    推荐文章