所以,count会直接算
引用
In Ruby, #length and #size are synonyms and both do the same thing: they tell you how many elements are in an array or hash. Technically #length is the method and #size is an alias to it.
In ActiveRecord, there are several ways to find out how many records are in an association, and there are some subtle differences in how they work.
post.comments.count - Determine the number of elements with an SQL COUNT query. You can also specify conditions to count only a subset of the associated elements (e.g. :conditions => {:author_name => "josh"}). If you set up a counter cache on the association, #count will return that cached value instead of executing a new query.
post.comments.length - This always loads the contents of the association into memory, then returns the number of elements loaded. Note that this won't force an update if the association had been previously loaded and then new comments were created through another way (e.g. Comment.create(...) instead of post.comments.create(...)).
post.comments.size - This works as a combination of the two previous options. If the collection has already been loaded, it will return its length just like calling #length. If it hasn't been loaded yet, it's like calling #count.
That's I always have to look up these differences, so now I have them in one place so I don't have to think about it anymore.
分享到:
相关推荐
InspiniaAdmin 2.6.1 Rails_Full_Version
rails_semantic_logger, Rails 语义记录器用语义记录器替换 Rails 缺省记录器 Rails 语义记录器 语义记录器用语义记录器替代 Rails 缺省记录器。http://github.com/rocketjob/rails_semantic_logger文档有关完整文档...
inspinia admin 2.5 中的 Rails_Full_Version
rails_apps_composer, 一个 gem,为 Rails 启动应用程序创建 Rails 应用程序模板 Rails 应用编辑器 Rails 应用程序编辑器 gem 安装一个 命令行 工具来从"食谱"的Collection 组装 Rails 应用程序。"你可以使用 rails_...
agile_web_development_with_rails_3rd_edition.9994652073.pdf
RestFul_Rails_Dev_v_0.1 RestFul_Rails_Dev_v_0.1
rails_best_practices ...默认情况下,rails_best_practices将解析vendor , spec , test和features目录中的代码。 排除目录 要排除目录,只需使用-e或--exclude调用: rails_best_practices -e "db/migrate
Rails_Recipes_with_Source_Code
ruby_on_rails_3_入门教程(中文)
Rails_3_Cheat_Sheets.pdf
InspiniaAdmin 2.5 Rails_Seed_Project
rails_plugins_presentation
InspiniaAdmin 2.5 Rails_full_version
自述文件 该自述文件通常会记录启动和运行应用程序所需的所有步骤。 您可能要讲的内容: Ruby版本 系统依赖 配置 数据库创建 数据库初始化 如何运行测试套件 服务(作业队列,缓存服务器,搜索引擎等) ...
介绍插件,用于对记录进行排序(使用 gem)安装要启用rails_admin_acts_as_list,请将以下内容添加到您的Gemfile : gem 'rails_admin_acts_as_list'gem 'rails_admin' 重要提示: rails_admin_acts_as_list之前必须...
has_many:通过 这是关于如何使用has_many :throght创建多对多关联的完整示例has_many :throght在此示例中,我使用staff模型和client模型,其中人员有很多客户,而客户有很多员工 操作说明 在下面的终端中输入 $ ...
复杂Rails系统架构优化
INSPINIA_Rails_Full_Version-v2.6.2.1