我有一个模特
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)
立即求值的正确方法是什么?