在 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/