如何执行读取已保存和未保存数据的查询?

How do you execute a query reading both saved and unsaved data?

提问人:Adam 提问时间:8/8/2023 最后编辑:Mark RotteveelAdam 更新时间:8/12/2023 访问量:33

问:

我的 rails 应用程序根据多个表中的数据确定库存限制。例如,我对箱子里的东西有重量和空间限制,对板条箱中可以装多少个箱子有限制,等等。确定是否超出限制的计算需要来自多个表的数据,并且每个表需要多个记录。

class Item < ApplicationRecord
  # Item has an database field for weight.
  belongs_to :box
end

class Box < ApplicationRecord
  # Box has an database field for weight_limit and weight.
  has_many :items

  def weight_limit_check()
    if( items.any? { |item| item.weight > weight_limit } )
      return false
    end

    return true
  end

  def weight()
    return items.reduce( 0 ) { |sum, item| sum + item.weight } + weight
  end
end

class Crate < ApplicationRecord
  # Crate has an database field for weight_limit.
  has_many :boxes

  def weight_limit_check()
    if( boxes.any? { |box| box.weight > weight_limit } )
      return false
    end

    return true
  end
end

class CrateController < ApplicationController
  # GET /crate/:id/weight_limit_check
  def weight_limit_check()
    if( Crate.find( params[:id] ).weight_limit_check() )
      render :ok
    else
      render :not_acceptable
    end
  end
end

我想在这些计算中包含临时数据,而无需提供有关正在更改的所有详细信息。换句话说,我希望有一些东西来表示进行更改后数据库的外观,但不进行更改。这样做的原因是,我需要使用此处未列出的记录的其他属性,但这些属性可能会受到现有记录和临时记录的影响。

class CrateController < ApplicationController
  # GET /crate/:id/weight_limit_check
  def weight_limit_check()
    if( Crate.find( params[:id] ).weight_limit_check( params[:additional_boxes_with_stuff] ) )
      render :ok
    else
      render :not_acceptable
    end
  end
end

是否可以暂存对任意数量的表进行更改,从而允许计算运行,就好像它从数据库中读取新数据一样,但不保存该新数据?

class Crate < ApplicationRecord
  ...

  def weight_limit_check( additional_boxes_with_stuff )
    ...Somehow include the additional_boxes_with_stuff in the calculation...

    if( boxes.any? { |box| box.weight > weight_limit } )
      return false
    end

    return true
  end
end

在研究此问题的解决方案时,我可以看到我可能会使用事务来应用数据,调用函数来运行计算,然后在事务块中抛出异常以防止保存更改。虽然这似乎是可行的,但我不确定这是否是最好的解决方案。

Ruby-on-Rails 数据库

评论

0赞 smathy 8/8/2023
真的不清楚你的情况是什么,为什么计算需要写操作是一个谜。请查看“如何提出一个好问题?”,尤其是“如何创建最小的、可重现的示例”部分。投票决定关闭。
0赞 engineersmnky 8/8/2023
我同意@smathy目前还不清楚您要做什么,尤其是在没有代码的情况下,但也许您正在寻找类似“ActiveModel::D irty?这将向您显示将在保存时应用的更改,这似乎涉及您的一些观点。

答: 暂无答案