ruby - Rails 4: Modify eager load query when using .includes(:association) -


i have 2 models:

class user < activerecord::base   has_many :purchases    # perform joins , attach calculations user object   scope :add_stats, -> { group("users.id").joins(:purchases).select("users.*, sum(purchases.price) total_purchases") } end  class purchase < activerecord::base   belongs_to :user end 

the add_stats scope represents heavy calculations attached user objects. if want user objects stats, write user.all.add_stats.

so far good. want fetch purchase objects , eager load users with stats well. i've tried this:

belongs_to :user, -> { add_stats }

but when rails eager load users, seems remove .group("user.id").joins(:purchases) , complain on purchases.price - "purchases table unknown". .select() thing preserved scope.

how apply scope (with working .group().joins()) eager load query of included belongs_to :user objects?

i tried in rails4 app , works

class user < activerecord::base   scope :add_stats, -> { group("users.id").joins(:events).select("users.*, sum(events.id) total_events") }  class event   belongs_to :user, -> { add_stats } 

in rails console

event.includes(:users).first.user.total_events reloading...   event load (0.1ms)  select "events".* "events" "events"."label" = 'hamburg' order "events"."id" asc limit 1   participant load (0.3ms)  select "participants".* "participants" "participants"."event_id" in (2)   user load (0.3ms)  select "users".* "users" "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) total_events "users" inner join "events" on "events"."user_id" = "users"."id" "users"."id" = ? group users.id order "users"."id" asc limit 1  [["id", 2]] => 68  event.first.user.total_events reloading...   event load (0.2ms)  select "events".* "events" "events"."label" = 'hamburg' order "events"."id" asc limit 1   user load (0.2ms)  select users.*, sum(events.id) total_events "users" inner join "events" on "events"."user_id" = "users"."id" "users"."id" = ? group users.id order "users"."id" asc limit 1  [["id", 2]] => 68 

i guess not want, not use scope include.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -