【发布时间】:2014-02-01 00:13:26
【问题描述】:
我如何在父对象中记忆一个昂贵的查询并在子对象中重用它?我面临的问题是,每次我从子级到父级进行引用:child1.parent 或 child2.parent 时,它都会给出不同的对象 ID,并且不会发生记忆。
class Post
has_many :comments
def total_comments
unless @total_comments
puts "Loading comments"
@total_comments = comments.count
end
@total_comments
end
end
class Comment
belongs_to :post
def total_comments
post.total_comments
end
end
post.comments[0].total_comments
post.comments[1].total_comments
这应该只查询一次 cmets,但因为它没有在加载两次的同一个对象上记忆
Loading comments...
Loading comments...
【问题讨论】:
标签: ruby-on-rails activerecord memoization