無論如何,我能夠通過將線以下轉換SQL查詢到Rails的活動記錄查詢
group = UserGroup.find_by_sql("select user_group_memberships.user_group_id, sum(-bets.amount + bets.amount_paid) as bankroll_net_profit from bets inner join user_group_memberships ON bets.user_id = user_group_memberships.user_id GROUP BY user_group_memberships.user_group_id")
它提供了以下結果來獲取導致鐵軌控制檯:
-+-----------------------------------+
| user_group_id | bankroll_net_profit |
+---------------+---------------------+
| 1 | 4765 |
| 57 | 1517 |
| 58 | -20 |
| 62 | 1517 |
| 64 | 1517 |
| 66 | 1507 |
| 67 | 995 |
| 82 | 1517 |
-+-----------------------------------+
但是我需要去活動記錄groups
變量,但我得到Array
(通過group.class
檢查),所以我不能在活動記錄中進行額外的計算。
能anybuddy幫我找上面MySQL查詢的活動記錄:我需要Model.joins(:another_model)
協會低於:
class UserGroup < ActiveRecord::Base
has_many :user_group_memberships
has_many :users, :through => :user_group_memberships
class User < ActiveRecord::Base
has_many :user_group_memberships
has_many :user_groups, :through => :user_group_memberships
class Bet < ActiveRecord::Base
belongs_to :user