强制评估active_record查询

时间:2020-04-25 00:59:54

标签: activerecord

我有一个模特

class Country
  has_many :graphs
end

class Graph
  has_one_attached :total_plot
  has_one_attached :delta_plot
end

当我创建带有附件total_plot的新图形时,我想删除所有带有附件total_plot的旧图形。在country.rb模型中,我的代码如下

old_graphs = graphs.joins(:total_plot_attachment)
graph = Graph.make_a_new_total_plot #creates a new graph with a total_plot attached
old_graphs.destroy_all

但这不起作用,可能是因为old_graphs.destroy_all不仅删除了old_graphs而且删除了new graphs。我认为正在发生的事情是old_graphs是延迟加载的,并且仅在执行old_graphs.destroy_all时才进行评估,而此时新图包含在联接中,因此被删除。

如果我在第一行后放置一个类似puts "old_graphs: #{old_graphs.map(&:id)}"的语句,它将强制求值并且代码可以工作,但是强制Graphs.joins(:total_plot_attachment)立即求值的正确方法是什么?

0 个答案:

没有答案