Key.select('products.name as product, product_groups.name as product_group, AVG(keys.cost) as cost')
.group('products.id, product_groups.id')
.left_joins(:product,:product_group)
結果缺少柱:的Rails ActiveRecord的:在分組查詢
=> #<ActiveRecord::Relation [#<Key id: nil, cost: 0.6e1>, #<Key id: nil, cost: 0.4e1>]>
預期回報3場,但returnig值:2字段。
I found the solution. The detail areas in the console did not appear as HASH.
每個表中的數據是什麼?並且正在生成什麼SQL? (您可以通過查看日誌,或在查詢末尾添加'.to_sql'來輕鬆查看。) –
SELECT product.name as product,product_groups.name as product_group,AVG(keys.cost)as cost FROM keys LEFT OUTER JOIN products on products.id = keys.product_id LEFT OUTER JOIN product_groups ON product_groups.id = keys.product_group_id GROUP BY products.id,product_groups.id –
...每個表中的數據是什麼? [編輯你的文章](http://stackoverflow.com/posts/43629465/edit)包含所有信息。回答提供[最小,**完整**和**可驗證**示例]的問題(https://stackoverflow.com/help/mcve)要容易得多。 –