【问题标题】:Why is ActiveRecord objects.size returning the wrong number?为什么 ActiveRecord objects.size 返回错误的数字?
【发布时间】:2013-03-18 03:08:26
【问题描述】:

我在 School 对象和通过 has_many :through, :uniq => true 关系连接的 User 对象之间有一个 ActiveRecord。

在学校课堂上,我有一个特定的方法来查询学生:

def students
  self.users.where(educations: {end_date: nil})
end

这似乎正确地只给了我唯一的用户(无重复),但奇怪的是school.students.size 给了我一个包含重复记录的计数!但是,如果我查看 school.students 返回的可枚举,它只显示唯一记录。

我尝试在 where 查询的末尾添加 #uniq。这似乎不能解决问题。到目前为止,我唯一的解决方案是使用school.students.compact.size,但这不可能。

顺便说一句,school.users.size 给了我一个准确的计数。

【问题讨论】:

  • 能否请您也分享一个要点?

标签: ruby-on-rails ruby-on-rails-3 activerecord rails-activerecord


【解决方案1】:

您应该在 ActiveRecord::Relation 对象上使用count,因为它可以对数据库进行计数查询。调用size 会导致从数据库中获取所有对象,创建一个数组,然后调用size。不过,这可能无法解决您的问题。

创建另一个关联有影响吗?

has_many :students, class_name: User, through: SchoolUsers(?), conditions: {educations: {end_date: nil}}

【讨论】:

  • 我会试试的。 #length 可以正常工作,但 #count 不能。我猜#size & #count 不是计算数组的大小,而是对数据库进行计数查询。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-08
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
相关资源
最近更新 更多