2016-09-21 4 views
0

を使用して、メインモデルのためのメタデータとして加入の数を選択する方法:Railsは、私はアイテムの数と一緒にアクティブなユーザーを選択します使用し私のようなものです二つのテーブル持っているのActiveRecord

users 
    id 
    name 
    active 

items 
    id 
    user_id 
    color 

を赤または青です。私は結果はユーザーが項目の注釈付きの数を持っているユーザーの配列になりたい

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

リターンその関連item数とuser_idのリスト言いません:

{ 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 

赤と青をカウントしかし、REDとBLUEは特別であり、一般的に参照する場合は、あなたが行うことができますこの...

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

Dそして、あなたは0赤や青のアイテムを持っているユーザーが含まれるようにしたいですので

@users = User.active.preload(:red_and_blue_items) 
ビューで

@users.first.red_and_blue_items.size 
関連する問題