了解 rails 大小与计数,以及为什么 .size 在视图中不起作用?

Understanding rails size vs count, and why .size doesn't work in view?

当我使用 .count 方法时,它工作得很好并且准确地显示了帖子数。当我尝试 .size 时,它​​会抛出一个错误。这是为什么?

我的 static_controller.rb 代码(使用 COUNT 作为方法)

class StaticController < ApplicationController

def index
@post_count = Post.count
@user_count = User.count
end

index.html.erb(使用 COUNT 作为方法)

<div>
      <p> <%= @post_count %> </p>
</div>

当我将 .count 的实例更改为 size 时,我在本地服务器中收到此错误:

NoMethodError 在 / #

的未定义方法“大小”

index - app/controllers/static_controller.rb,第 4 行

这是为什么? .size 不是 rails 的内置方法吗?如果没有,我该如何解决这个问题?

此外,如果将 counter_cache 应用于该方法所应用的模型,我是否正确理解 .size 性能更高?例如,如果我的 post.rb 模型有一个部分声明了 counter_cache,那会自动使它变得更 fast/performant 吗?

count 是一种 AR 方法,它会在 SQL 查询中使用 COUNT,它实际上让 AR 知道你在做数据库查询,它 return计数值 return 由数据库编辑。

Size 是集合的方法,Post 和 User 是 类,不是集合,所以从不使用 AR,最终会报错,因为你首先需要做一个AR 查询有一个集合,即使是一个空集合。

rails 方法是使用 all,这将 return 一个集合。

@post_count = Post.all.size
@user_count = User.all.size

类似的方法有3种:

  • count 正在使用 SQL 查询。这是最快的方法,但正如您所注意到的,并不总是可以执行。

  • 如果集合已加载,
  • length 将 return 集合的长度而不执行其他查询。它可能无效,因为它会将整个集合加载到内存中。

  • size 它是 countlength 的组合。只有在卸载集合时才会执行额外的查询。