Rails查询与嵌套关联和组(由关联对象)

时间:2017-02-18 08:20:55

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord

鉴于此模型关系:

sss=StratifiedShuffleSplit(n_splits=n_splits,test_size=test_size,
    train_size=train_size,random_state=random_state).split(all_groups,all_labels) 
        # startified splitting for groups only

i=0
train_is = [np.array([],dtype=int)]*n_splits
test_is = [np.array([],dtype=int)]*n_splits
for train_index,test_index in sss :
        # finding the corresponding indices of reflected training and testing sets
    train_is[i]=np.hstack((train_is[i],np.concatenate([train_index*6+i for i in range(6)])))
    test_is[i]=np.hstack((test_is[i],np.concatenate([test_index*6+i for i in range(6)])))
    i=i+1

cv=[(train_is[i],test_is[i]) for i in range(n_splits)]
        # constructing the final cross-validation iterable: list of 'n_splits' tuples;
        # each tuple contains two numpy arrays for training and testing indices respectively

opt=GridSearchCV(SVC(decision_function_shape=dfs,tol=tol),param_grid=param_grid,
                 scoring=scoring,n_jobs=n_jobs,cv=cv,verbose=verbose)
opt.fit(allr_sets_nor[:,:2],allr_labels)

我想计算每家公司的所有订单,所以我得到了这个:

orders.rb
belongs_to user

user.rb
belongs_to company

company.rb
has_many users

,结果是

[“公司1”,1] => 123

但我不知道如何更改此查询

Order.joins(user: :company)
.group(['companies.name, companies.id])
.count

而不是公司属性的数组。

1 个答案:

答案 0 :(得分:2)

通过向模型添加另一个关联可以使这更容易:

# company.rb
has_many :users
has_many :orders, through: :users

然后你可以这样做:

   companies = Company.
               joins(:orders).
               group("company.id").
               select("company.id, company.name, count(orders.id) as orders_count")

如果您说companies.first,您会看到类似的内容:

#<Company:0x005610fa35e678 id: 15 name: 'foo'>

它看起来不像orders_count。但它实际上已经加载了。你可以这样得到它:

companies.first.orders_count

如果您将公司转换为哈希值,您也可以看到它:

companies.first.attributes # => { id: 15, orders_count: 2, name: "foo" }

至少在Postgres中,如果要在属性哈希中获取更多数据,则必须单独指定select字符串中的每个列。我不确定其他数据库。