以下是代码:
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
有没有办法将此减少到只有一个数据库调用?
答案 0 :(得分:0)
尝试使用includes
或join
。这将创建一个SQL
查询,根据您的喜好创建表和组之间的连接。
a.includes(:videos => :video_types).group('video_types.video_type_name')