[英]what is the best way to know whether the association is present or not?
i have to check user
has photos
or not, so i am doing 我必须检查
user
是否有photos
,所以我在做
current_user.photos.blank?
it works good, but this is very ineffective since it loads all photos
into memory (not sure, correct me if i'm wrong). 它的效果很好,但这是非常无效的,因为它将所有
photos
加载到内存中(不确定,如果我错了,请纠正我)。
I don't want to do this because it will crash my server if 我不想这样做,因为如果
current_user.photos.blank?
current_user.photos.blank?
type of conditions exists, so all this code demands the memory and I guess my server will crash. I just want to check association ( photos
) is present or not effectively, that's all? 我只想检查关联(
photos
)是否存在或无效,仅此而已?
What is the best way to do it? 最好的方法是什么?
You can use ActiveRecord
's exists? 您可以使用
ActiveRecord
的存在吗? or any?
还是
any?
method to do what you want. 做你想要的方法。 This won't return a collection of objects and thus it won't load possible
photos
on memory. 这不会返回对象的集合,因此不会将可能的
photos
加载到内存中。 It will just let you know whether a user
has any photos or not (true or false). 它只会让您知道
user
是否有照片(对还是错)。
So for your example, you could have something like this: 因此,对于您的示例,您可能会遇到以下情况:
current_user.photos.any?
At a lower level, exists?
在较低的级别,
exists?
and any?
还有
any?
are limiting their queries (via SQL's LIMIT
) to a single result so they can efficiently answer your question. 将他们的查询(通过SQL的
LIMIT
) LIMIT
为单个结果,以便他们可以有效地回答您的问题。
present?
, on the other hand, will return all matching objects which might be an unnecessary load in your case but could serve better for other cases where the matching objects are supposed to be used in some way (eg iterating over them shortly after checking for their existence). 另一方面,将返回所有匹配的对象,这在您的情况下可能是不必要的负载,但在应该以某种方式使用匹配的对象的其他情况下(例如,检查它们的存在后不久对其进行迭代)可能会更好)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.