ste*_*ddy 3 doctrine ruby-on-rails rails-activerecord
我在这里size了解了,count和的用法差异。当我这样使用它时,这是有道理的:length
@posts = Post.all
puts "length: ", @posts.length
puts "count: ", @posts.count # Makes a database call to count records
puts "size: ", @posts.size
Run Code Online (Sandbox Code Playgroud)
所有三个都返回正确的长度。但是,如果我在上面的代码片段中替换@posts = Post.all
为 ,我会收到帖子对象的大小、计数和长度错误@posts = Post.find_by(post_type: 'article')noMethodError#<Post:>
find_by呢?当您使用Post.all它时,它会返回一个ActiveRecord::Relation实例 - 其行为与Array. 因此您可以使用、或等Array操作。countlengthsize
但length选择所有记录,加载到内存中并按常规计数Array。因此使用它效率低下并且灰心丧气。
但是当您使用find_by它时,它会返回符合指定条件的第一条记录。所以,length或count不会size起作用。你可以在这里读到它。
如果您想获取与您的查询匹配的所有记录,您最好使用where
Post.where(post_type: 'article').count
Run Code Online (Sandbox Code Playgroud)
您可以在此处了解有关如何使用条件的更多信息。
| 归档时间: |
|
| 查看次数: |
3464 次 |
| 最近记录: |