我有两个表格如下:
users
id
name
active
items
id
user_id
color
使用Rails,我想选择活跃用户以及红色或蓝色的项目数。
类似的东西:
User.where(active: true).joins(:items).where(items: {color: ['red', 'blue']}).count(:items)
我希望结果是一个用户数组,其中用户有一个带注释的项目数。
所以最终可能会像users = activerecord query ,users.first.name ==' John',users.first.items_count == 3
你会做什么?
答案 0 :(得分: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,
...
}
答案 1 :(得分: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
但是,如果RED和BLUE是特殊的并且通常被引用,那么你可以这样做......
class User
...
has_many :red_and_blue_items, where -> ({color: ["red", "blue"]}), class_name: "Item"
end
然后,像这样预加载
@users = User.active.preload(:red_and_blue_items)
在视图中
@users.first.red_and_blue_items.size