activerecord - Rails: Enumerable#group_by with Delegation makes too many DB calls -


here code:

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 

console:

a = athlete.last a.videos.group_by(&:video_type_name)   videotype load (0.8ms)  select "video_types".* "video_types" "video_types"."id" = 12 limit 1 called from: app/models/video.rb:9:in `video_type_name'   videotype load (0.9ms)  select "video_types".* "video_types" "video_types"."id" = 14 limit 1 called from: app/models/video.rb:9:in `video_type_name'   videotype load (0.8ms)  select "video_types".* "video_types" "video_types"."id" = 1 limit 1 called from: app/models/video.rb:9:in `video_type_name'   videotype load (0.7ms)  select "video_types".* "video_types" "video_types"."id" = 9 limit 1 called from: app/models/video.rb:9:in `video_type_name'   videotype load (0.7ms)  select "video_types".* "video_types" "video_types"."id" = 11 limit 1 called from: app/models/video.rb:9:in `video_type_name'   videotype load (0.8ms)  select "video_types".* "video_types" "video_types"."id" = 2 limit 1 called from: app/models/video.rb:9:in `video_type_name'   videotype load (0.8ms)  select "video_types".* "video_types" "video_types"."id" = 2 limit 1 

is there way reduce 1 database call?

try using includes or join. create sql query create joins between tables , group whatever like.

a.includes(:videos => :video_types).group('video_types.video_type_name') 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -