ruby-on-rails - 检查 ActiveRecord 集合中是否有记录的正确方法

标签 ruby-on-rails activerecord

在我看来,我有这样的代码:

<% 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/

相关文章:

ruby-on-rails - 减去两个时间范围

ruby-on-rails - 将 Rails View 呈现为电子邮件字符串

mysql - 如何在 Ruby on Rails 中连接 MySQL 表?

ruby-on-rails - rails in_groups 和 in_groups_of 有什么区别?

ruby-on-rails - 为什么 Rails 隐藏了 id 列的存在?

ruby-on-rails - 模型中的 rails url helper

ruby-on-rails - Resque缓存事件记录校准

ruby-on-rails - 如何设置Rails Associations::Preloader的预加载范围?

sql - Codeigniter Active Record - 删除不在数组中的位置

ruby-on-rails - Ruby on Rails 集成测试期间间歇性 ActiveRecord::RecordNotFound