2016-09-21 83 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