0

我有两个模型:

class User < ActiveRecord::Base
  has_many :purchases

  # Perform joins and attach some calculations to the User object
  scope :add_stats, -> { group("users.id").joins(:purchases).select("users.*, SUM(purchases.price) AS total_purchases") }
end

class Purchase < ActiveRecord::Base
  belongs_to :user
end

add_stats范围表示附加到User对象的繁重计算。因此,如果我想获取所有User具有统计信息的对象,我只需编写User.all.add_stats.

到目前为止,一切都很好。现在我想获取一些Purchase对象并急切地加载带有统计信息User的s 。我试过这个:

belongs_to :user, -> { add_stats }

但是当 Rails 急切地加载用户时,它似乎删除.group("user.id").joins(:purchases)并抱怨purchases.price- “购买表未知”。因此,这.select()是从范围中保留的唯一内容。

如何将范围(使用 working .group().joins())应用于所有包含belongs_to :user对象的急切加载查询?

4

1 回答 1

0

我刚刚在我的 rails4 应用程序中尝试过,它可以工作

class User < ActiveRecord::Base
  scope :add_stats, -> { group("users.id").joins(:events).select("users.*, SUM(events.id) AS total_events") }

class Event
  belongs_to :user, -> { add_stats }

在导轨控制台中

Event.includes(:users).first.user.total_events
Reloading...
  Event Load (0.1ms)  SELECT "events".* FROM "events" WHERE "events"."label" = 'hamburg' ORDER BY "events"."id" ASC LIMIT 1
  Participant Load (0.3ms)  SELECT "participants".* FROM "participants" WHERE "participants"."event_id" IN (2)
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" IN (1, 2, 3, 4, 8, 10, 11, 12, 14, 16, 17, 18, 19, 20)
  User Load (0.3ms)  SELECT users.*, SUM(events.id) AS total_events FROM "users" INNER JOIN "events" ON "events"."user_id" = "users"."id" WHERE "users"."id" = ? GROUP BY users.id ORDER BY "users"."id" ASC LIMIT 1  [["id", 2]]
=> 68

Event.first.user.total_events
Reloading...
  Event Load (0.2ms)  SELECT "events".* FROM "events" WHERE "events"."label" = 'hamburg' ORDER BY "events"."id" ASC LIMIT 1
  User Load (0.2ms)  SELECT users.*, SUM(events.id) AS total_events FROM "users" INNER JOIN "events" ON "events"."user_id" = "users"."id" WHERE "users"."id" = ? GROUP BY users.id ORDER BY "users"."id" ASC LIMIT 1  [["id", 2]]
=> 68

我想这不是你想要的,因为这不使用包含的范围。

于 2013-10-06T16:50:49.057 回答