【发布时间】:2018-10-13 20:24:22
【问题描述】:
是否可以通过对包含 has_many 关联的 SQL 查询的记忆来缓存实例变量?在下面的两个示例方法中, some_instance 方法将按预期进行缓存,但 some_other_instance 将缓存 Artist 而不是歌曲关联,这会导致每次运行该方法时都会进行 SQL 查询。
当方法返回“ActiveRecord::Associations::CollectionProxy”或“ActiveRecord::Relation”时,它似乎不会完全缓存。
class Artist < ApplicationRecord
has_many :artist_songs
has_many :songs, through: :artist_songs
def self.some_instance
@some_instance ||= find(10)
end
def self.some_other_instance
@some_other_instance ||= find(10).songs
end
end
【问题讨论】:
-
说“第一次工作正常”你真的是说它不使用
select * from songs ...SQL 查询对songs表执行选择吗? “第二个仍将执行 SQL 查询”-您到底在说哪个查询?如果您对在第二种方法中找到Artist的查询感到恼火,那么只需使用第一种方法来记忆它:@some_other_instance ||= some_instance.songs。 -
抱歉不清楚。 “some_instance”方法会缓存变量,并且在再次运行该方法时不会执行更多 SQL 查询。 “some_other_instance”方法缓存了 Artist,但不缓存歌曲关联,所以当再次运行该方法时,我看到了歌曲集合的 SQL 查询。
-
我刚刚尝试了您关于重写“some_other_instance”方法的建议,但不幸的是遇到了同样的问题。
-
你能显示你对
some_other_instance方法的两次调用的输出吗?
标签: ruby-on-rails