0

这是代码:

class Video < ActiveRecord::Base
  delegate :name, :to => :video_type, :prefix => true, :allow_nil => true
  belongs_to :athlete, :class_name => "Athlete"
end

class Athlete < User
  has_many :videos
end

安慰:

a = Athlete.last
a.videos.group_by(&:video_type_name)
  VideoType Load (0.8ms)  SELECT "video_types".* FROM "video_types" WHERE "video_types"."id" = 12 LIMIT 1
Called from: app/models/video.rb:9:in `video_type_name'
  VideoType Load (0.9ms)  SELECT "video_types".* FROM "video_types" WHERE "video_types"."id" = 14 LIMIT 1
Called from: app/models/video.rb:9:in `video_type_name'
  VideoType Load (0.8ms)  SELECT "video_types".* FROM "video_types" WHERE "video_types"."id" = 1 LIMIT 1
Called from: app/models/video.rb:9:in `video_type_name'
  VideoType Load (0.7ms)  SELECT "video_types".* FROM "video_types" WHERE "video_types"."id" = 9 LIMIT 1
Called from: app/models/video.rb:9:in `video_type_name'
  VideoType Load (0.7ms)  SELECT "video_types".* FROM "video_types" WHERE "video_types"."id" = 11 LIMIT 1
Called from: app/models/video.rb:9:in `video_type_name'
  VideoType Load (0.8ms)  SELECT "video_types".* FROM "video_types" WHERE "video_types"."id" = 2 LIMIT 1
Called from: app/models/video.rb:9:in `video_type_name'
  VideoType Load (0.8ms)  SELECT "video_types".* FROM "video_types" WHERE "video_types"."id" = 2 LIMIT 1

有什么办法可以将其减少到只有一个数据库调用?

4

1 回答 1

0

尝试使用includesjoin。这将创建一个SQL查询,根据您的喜好创建表和组之间的连接。

a.includes(:videos => :video_types).group('video_types.video_type_name')
于 2013-08-23T18:12:21.247 回答