0

Similar to will_paginate with named_scopes but not getting an error - rather unexpected results. Rails version 4.

If I have a scope in a Foo model (where a user has_many: foos) - models/foo.rb:

belongs_to :user
scope :hasCars, -> { joins(:cars) }

And now try use the scope with will_paginate (in the controller):

@foos = auser.foos.hasCars.paginate(:page=>1,:per_page=>20)

Then the view duplicates each foo by the number of cars they have in the :through ownership association - so for foo 1 - 4 of a given user:

foo1.cars.size # =>1
foo2.cars.size # =>4
foo3.cars.size # =>0
foo4.cars.size # =>2

View:

foo1
foo2
foo2
foo2
foo2
foo4
foo4

Works as expected without the paginate and paginate works fine without the scope.

The association of Foo to cars is :through => :ownership. I guess it's to do with the way the scope is created using a join and how that join is passed to will_paginate. This is the query I see in the logs:

SELECT "".* FROM "foos" INNER JOIN "ownership" ON "ownership"."foo_id" = "foos"."id" INNER JOIN "cars" ON "car"."id" = "ownership"."car_id" WHERE "foos"."user_id" = ? [["user_id", 1]]

This should return the correct number of rows. But then for each car owned by Foo, I see a query cars from cars where foo_id = X being duplicated, am guessing from a query generated by will_paginate

Is there a better way to create the scope? Or should will_paginate be set up differently? Or could this be a will_paginate bug?

I have tried using joins(:ownership) too in the scope - same behaviour.

Community
  • 1
  • 1
Brett
  • 5,690
  • 6
  • 36
  • 63

1 Answers1

0

Found the answer here:

Rails will_paginate shows duplicates on HABTM models

auser.foos.hasCars.group("car_id").paginate...
Community
  • 1
  • 1
Brett
  • 5,690
  • 6
  • 36
  • 63