2016-09-21 35 views
0

我有两个表是像作为主模型元数据加入:如何选择计数的使用ActiveRecord

users 
    id 
    name 
    active 

items 
    id 
    user_id 
    color 

使用Rails,我想选择的活跃用户与项目的数量一起红色或蓝色。

喜欢的东西:

User.where(active: true).joins(:items).where(items: {color: ['red', 'blue']}).count(:items) 

我想要的结果是当用户有项目的注释号码的用户的数组。

所以它最终可能像用户= ActiveRecord的查询,users.first.name == '约翰',users.first.items_count == 3

你会怎么做?

+0

难道被列入? – Swards

回答

0

我不说这是解决方案,但此声明如下

Item .joins(:user) .group(:user_id) .where(users: { active: true }, color: ['red', 'blue']) .count

回报user_id与其关联item计数的列表:

{ user_id_1 => count_1, user_id_2 => count_2, user_id_3 => count_3, ... }

0

考虑颜色过滤器,我只是用红宝石做计数。

class User 

    scope :active, -> { where(active: true) } 

    def items_of_color(colors) 
    items.select{ |i| i.color.in?(colors) } 
    end 

end 
控制器

@users = User.active.preload(items) 

,然后在视图中,计数红色和蓝色

user.items_of_color(['red', 'blue']).size 

但是,如果红色和蓝色是特殊的,经常引用的,你可以做这...

class User 
    ... 
    has_many :red_and_blue_items, where -> ({color: ["red", "blue"]}), class_name: "Item" 
end 

An d然后,预装像这样

@users = User.active.preload(:red_and_blue_items) 

在视图中你想要的有0红色或蓝色物品的用户

@users.first.red_and_blue_items.size 
相关问题