gpt4 book ai didi

ruby-on-rails - 在模型实例上强制加载关联

转载 作者:行者123 更新时间:2023-12-03 17:35:12 25 4
gpt4 key购买 nike

考虑一下:

class Post < ActiveRecord::Base
has_many :comments

def last_comment
comments.last
end
end

railsconsole> p = Post.last
Post Load (0.2ms) SELECT `posts`.* FROM `posts` WHERE ORDER BY `posts`.`id` DESC LIMIT 1
railsconsole> p.last_message
Post Load (0.4ms) SELECT `comments`.* FROM `comments` WHERE `messages`.`post_id` = 14
railsconsole> p.last_message
Post Load (0.4ms) SELECT `comments`.* FROM `comments` WHERE `messages`.`post_id` = 14

您会认为这里应该只发生 2 个查询:初始查找,然后是关联的加载。对关联的后续调用应该被缓存。然而,他们不是。关联永远不会被加载和缓存,因为 Rails 试图变得聪明并且只加载最后一条记录。由于 Rails 不跟踪最后一条记录(或第一条或任何其他对关联的进一步自定义查询),它每次只返回答案。

但是,如果您想缓存关联怎么办?我搜索了 SO,但找不到直接答案。

最佳答案

当您在 ActiveRecord 实例上调用关联时,您将获得一个代理对象,而在 has_many 对象的情况下,您将获得一个 CollectionProxy。

奇怪的是,您可以在集合代理上调用 #load ,但这不会加载关联缓存。

隐藏在 Rails 文档中:http://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-load_target

#load_target

|
class Post < ActiveRecord::Base
has_many :comments

def last_comment
comments.load_target unless comments.loaded?
comments.last
end
end

希望其他人觉得这很有用。

关于ruby-on-rails - 在模型实例上强制加载关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26415660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com