使用未保存的关联

Thi*_*kel 2 activerecord ruby-on-rails

假设我有两种型号:

class Model1 < ActiveRecord::Base
  has_many :model2

  def save
    self.attr = <sth. complex involving the associated model2 instances>
    super
  end
end

class Model2 < ActiveRecord::Base
  belongs_to :model1
end
Run Code Online (Sandbox Code Playgroud)

覆盖save方法中的语句将发出复杂查询(使用find[或替代命名的范围])来计算某些关联的Model2实例的某些聚合值.问题是当一个新的Model1实例和一些Model2实例一起使用时,该查询save在创建对象后不会返回任何内容,并且将返回所有连续save操作的旧数据(上一代).

有没有办法find在非持久的内存状态下使用?

Fra*_*eil 6

当然:它被称为#select,或#inject,或任何其他-ect方法:

class Model1 < ActiveRecord::Base
  has_many :model2

  before_save :update_aggregate_value

  private
  def update_aggregate_value
    # returns sum of unit_value for all active model2 instances
    self.attr = model2.select(&:active?).map(&:unit_value).sum
  end
end

class Model2 < ActiveRecord::Base
  belongs_to :model1
end
Run Code Online (Sandbox Code Playgroud)

请记住,在这种情况下,DB 不会被命中,除非尚未加载model2实例.另外,请注意我使用了before_save回调,而不是覆盖#save.这是"更安全",因为您可以返回false并阻止保存继续进行.