Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails RubyonRails中模型之间的交互逻辑?_Ruby On Rails_Ruby_Design Patterns_Refactoring_Models - Fatal编程技术网

Ruby on rails RubyonRails中模型之间的交互逻辑?

Ruby on rails RubyonRails中模型之间的交互逻辑?,ruby-on-rails,ruby,design-patterns,refactoring,models,Ruby On Rails,Ruby,Design Patterns,Refactoring,Models,我正在学习Rails,现在正试图组织模型之间的交互。我写的东西很管用,但我觉得代码很难闻 例如,我有两个带有数据库表packet和Warehouse的模型。创建新地块时,我希望增加与此新地块相关的仓库实例的:current_weight 再说一次,一切都正常,但是这种类型的代码,两个不同对象之间的交互,将被频繁使用,在我的脑海深处会有这样一句话:“老兄,这种代码很糟糕,将来会导致问题!” 也许有一些很好的实践来组织或重构它?也许是 最好为这种交互创建一个通用模块,甚至创建 method\u mi

我正在学习Rails,现在正试图组织模型之间的交互。我写的东西很管用,但我觉得代码很难闻

例如,我有两个带有数据库表
packet
Warehouse
的模型。创建新地块时,我希望增加与此新地块相关的仓库实例的
:current_weight

再说一次,一切都正常,但是这种类型的代码,两个不同对象之间的交互,将被频繁使用,在我的脑海深处会有这样一句话:“老兄,这种代码很糟糕,将来会导致问题!”

也许有一些很好的实践来组织或重构它?也许是 最好为这种交互创建一个通用模块,甚至创建
method\u missing
使用具有通用
put\u
remove\u
的方法的逻辑,
检查
,如
仓库。放置包裹
仓库。移除包裹

在ruby控制台中:

parcel = Parcel.new
parcel.weight = 10
parcel.warehouse_id = 1
parcel.save

# Create parcel and increase :current_weight of related warehouse by 10 after save
warehouse.rb:

class Warehouse < ActiveRecord::Base
    has_many :parcels
  attr_accessible :name, :current_weight
end
类仓库
parcel.rb:

class Parcel < ActiveRecord::Base
    belongs_to :warehouse
    belongs_to :vehicle
  attr_accessible :name, :weight, :warehouse_id, :vehicle_id

  after_save :set_current_weight

  #Bad code:
  def set_current_weight
    @wh = self.warehouse
    @wh.current_weight = @wh.current_weight + self.weight
    @wh.save
  end
end
类包
怎么样

warehouse.parcels.sum(:weight)
这样,您就可以基于当前数据运行“实时”查询,而不是增量查询

您当前模型的更简洁版本:

  def set_current_weight
    @wh = self.warehouse
    @wh.current_weight += self.weight
    @wh.save
  end

仓库的
当前_重量
实际上不是
包裹
对象授权的一部分。你也给了它不止一个改变的理由。因此,这打破了传统

我建议将
:当前权重
设置当前权重
一起删除。按如下方式获取仓库内的总重量:

def Warehouse < ActiveRecord::Base
  has_many :parcels
  # ...

  def current_weight
    parcels.sum(:weight)
  end
end
def仓库

正如@muttollamb在他的帖子中所建议的那样。

谢谢!那么,在地块模型中保存或更新地块后,是否应调用此“实时”查询?或者最好在仓库模型中实现它?如果仓库里有100500个包裹呢?这对SQL来说不是很重吗?就我个人而言,只要我想知道当前的权重,我就会运行查询。SUM命令对于100000行也不是特别“重”,尤其是在不进行任何其他数据操作的情况下。只是澄清一下,我并不是说在任何模型中将其定义为一种方法,底层逻辑是内置于ActiveRecord中的。