ruby-on-rails - 在查询中使用 'nil' 和 `group` 时,哈希值为 `count`

标签 ruby-on-rails database null

在 Rails 中,我使用 include 获得哈希值:

<% @teste = UserProfile.includes(:mobile_models).group(:name).count  %>

问题是 include 会生成如下所示的哈希值:

{nil=>4774, "2610"=>7, "2626"=>4, "2630"=>5, "2760"=>4, "3250"=>3, "355"=>5, "3I607 BlackJack"=>5, "5230"=>13, "5235"=>4, "5310"=>5, "5500"=>5, "5800 Xpress Music"=>16, "6020"=>4, "6120c"=>4, "6131"=>4, "7210"=>5, "A1200r"=>5, "A1900"=>5, "AIKO 70"=>5, "B3410W Ch@t"=>4, "beTouch E100"=>4, "BlackBerry 8320 (Curve)"=>10,....

在我的数据库中,我没有找到任何名为“nil”的移动记录。检查我的数据库,我找不到可能产生这个 nil 的原因。

另一个目标是对所有值求和,如下所示:

 <%= sum = @teste.values.sum %>

但是当我这样做时,也会添加“nil”。

---更新

模型/用户配置文件

class UserProfile < ActiveRecord::Base
  has_and_belongs_to_many :mobile_models, join_table: 'user_profiles_mobile_models', order: 'name'

模型/MobileModel

class MobileModel < ActiveRecord::Base
  belongs_to :mobile_maker

最佳答案

由于您按 :name 进行分组,因此某些 MobileModel 或 UserProfile 对象的 name 属性设置为 nil。您需要检查两者,因为没有看到模型定义,我无法判断哪个模型具有您正在分组的 :name 属性。如果您可以分享模型代码,我可以更明确。

如果两个模型都有 name 属性,您可以在组声明中更加明确:

UserProfile.includes(:mobile_models).group('mobile_models.name')

或者...

UserProfile.includes(:mobile_models).group('user_profiles.name')

此外,如果您的许多用户没有任何要包含的 mobile_models,我相信他们也会被转储到 nil 分组中。

关于ruby-on-rails - 在查询中使用 'nil' 和 `group` 时,哈希值为 `count`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23869640/

相关文章:

database-design - 关系数据库中的空值可以吗?

android - 如果未调用 setcontentview(),为什么 findViewById() 返回 null?

mysql - 如何获取连接中的对象?

ruby-on-rails - 如何通过 Rails 3.2 批量分配提交多个新项目

MySQL死锁问题

javascript - UPDATE SQL TABLE 使用绑定(bind)变量或绑定(bind)参数将新值减去存储值

ruby-on-rails - 将 ActiveRecord 列转换为 PostGIS 点

ruby-on-rails - 从 User.rb 模型访问 ApplicationHelper

sql-server - SQL Server UPDATE 语句不更新匹配约束的行

hadoop - 谁能告诉我为什么在使用to_date hive (1.2版)函数时为什么会为空?