maz*_*ing 6 ruby ruby-on-rails ruby-on-rails-3
当我使用 .count 方法时,它工作得很好并且准确地显示帖子数量。当我尝试 .size 时,它会抛出错误。为什么是这样?
我的 static_controller.rb 代码(使用COUNT作为方法)
class StaticController < ApplicationController
def index
@post_count = Post.count
@user_count = User.count
end
Run Code Online (Sandbox Code Playgroud)
index.html.erb(使用COUNT作为方法)
<div>
<p> <%= @post_count %> </p>
</div>
Run Code Online (Sandbox Code Playgroud)
当我将 .count 的实例更改为 时size
,我在本地服务器中收到此错误:
NoMethodError at / undefined method `size' for #
索引 - app/controllers/static_controller.rb,第 4 行
为什么是这样?.size 不是 Rails 的内置方法吗?如果没有,我该如何解决这个问题?
另外,如果将 counter_cache 应用于该方法所应用的模型,我是否正确理解 .size 的性能更高?例如,如果我的 post.rb 模型有一个声明 counter_cache 的部分,这是否会自动使其变得更快/性能更快?
count是AR的一个方法,它会COUNT
在SQL查询中使用,它实际上让AR知道你正在做一个数据库查询,并且它返回数据库返回的count值。
Size 是集合的一种方法,Post 和 User 是类,而不是集合,因此从不使用 AR,最终会出现错误,因为您首先需要执行 AR 查询才能获得集合,即使是空集合。
执行您尝试的操作的 Rails 方法是使用all
,它将返回一个集合。
@post_count = Post.all.size
@user_count = User.all.size
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2424 次 |
最近记录: |