我想检查一个对象是否包含一个或多个孩子:
if @question.replies.count > 0
// do this
else
// do that
end
但是我宁愿不进行涉及到的数据库查找。有没有一种很好的有效方法来做这个查询?
我想检查一个对象是否包含一个或多个孩子:
if @question.replies.count > 0
// do this
else
// do that
end
但是我宁愿不进行涉及到的数据库查找。有没有一种很好的有效方法来做这个查询?
如果您已经通过 加载回复include
,则可以使用@question.replies.length
或@question.replies.size
(更多信息在这里)。您还可以将您的if
陈述简化为
if @question.replies.present?
否则,您可以使用一个counter_cache
列,它只会在您的问题表 ( replies_count
) 上维护一个列,您可以随时访问该列。
只需使用:counter_cache(http://asciicasts.com/episodes/23-counter-cache-column)
如果您有预先加载的关联,请使用该present?
方法
class User
has_many :messages
end
class Message
belongs_to :user
has_many :replies
end
current_user.messages.all(:include => :replies).each do |message|
if message.replies.present?
else
end
end
如果您尚未将关联加载到内存中,请使用该exists?
方法。
current_user.messages.each do |message|
if message.replies.exists?
else
end
end
该exists?
调用导致EXISTS检查,该检查在找到第一个匹配行时返回,而不会产生从 DB 取回行数据的成本。
笔记
其他选择是使用@dimuch建议的counter_cache
方法。如果您可以更改数据库表结构,该解决方案将非常有效。counter_cache