在我看来,我有这样的代码:
<% if @posts.any? %>
<% @posts.each do |post| %>
...
<% end %>
<% else %>
<p>No posts found</p>
<% end %>
这在我的控制台日志中生成:
...
Post Exists (1.4ms) SELECT 1 AS one FROM `posts` LIMIT 1 OFFSET 0
...
Post Load (1.1ms) SELECT `posts`.* FROM `posts` LIMIT 50 OFFSET 0
...
所以这会在我的数据库上触发 2 个查询。如果我以这种方式改变 View
<% unless @posts.blank? %>
<% @posts.each do |post| %>
...
<% end %>
<% else %>
<p>No posts found</p>
<% end %>
只会触发一个查询:
...
Post Load (1.1ms) SELECT `posts`.* FROM `posts` LIMIT 50 OFFSET 0
...
如果我使用
@posts.exists?
或 @posts.empty?
或 @posts.any?
我执行两个查询,如果我使用 @posts.blank?
或 @posts.present?
我只执行一个查询。所以我的问题是:有一种最佳实践可以检查集合是否为空?我什么时候应该使用
exists?
, empty?
, any?
, present?
和 blank?
?
最佳答案
存在吗?应该使用它,因为它是最快的。
@post.blank? would retrieve all the post and count them.
!@post.present? would retrieve all the post and count them.
@post.empty? would retrieve the count of post.
空白?,现在?,空?如果您有预加载的记录,则可以很好地使用。
@post.any? would be exactly the same as the previous option.
任何?检索关系中的记录(除非它们被预加载),将它们表示为一个数组,然后调用。哪里存在?总是查询数据库,从不依赖预加载的记录,只检索一条记录,这使得这种方法比任何方法都快?
@post.exists? would retrieve the first post. That makes this approach fastest among those five.
关于ruby-on-rails - 检查 ActiveRecord 集合中是否有记录的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47771179/