无论如何,我可以通过在下面放置几行来在 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 查询的 Active Record:我需要 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