will_paginate with named_scopes

后端 未结 4 1968
野趣味
野趣味 2021-02-02 14:56

I\'m using will_paginate for pagination, which has been working well so far, except for this one thing.

If I try to paginate a scope, for instance

class          


        
4条回答
  •  遇见更好的自我
    2021-02-02 15:16

    Lowgain, it doesn't sound like you are, but just to make sure -- you aren't actually doing tests with a named_scope named scope right? Because scope is an existing method and using that as your scope name causes an error (and an infinite loop).

    EDIT:

    Does your named_scope happen to include a :limit clause? I just started having a similar problem. I have a model Response which belongs_to User, with a named scope something like this:

    named_scope :top, lambda { |limit| {
                :limit => limit,
                :order => 'total_score DESC' }}
    

    And I am seeing results in the console such as this:

    ?> u = User.find 1
    ?> u.responses.length
    => 9
    ?> u.responses.paginate(:page => 1, :per_page => 5).length
    => 5
    ?> u.responses.top(3).length
    => 3
    ?> u.responses.top(3).paginate(:page => 1, :per_page => 5).length
    => 5
    

    Yikes! How can my top 3 paginate to produce more than 3 rows? Per your example I tried your find(:all) trick with similar results:

    ?> u.responses.top(3).find(:all).paginate(:page => 1, :per_page => 5).length
    => 3
    

    This looks like a bug in named_scope, because I can take will_paginate out of the picture and get similar mayhem to occur:

    ?> u.responses.top(3).length
    => 3
    ?> u.responses.top(3).size
    => 9                       <-- .size produces wrong answer
    ?> r = u.responses.top(3)
    ?> r.size
    => 3                       <-- correct when result assigned to var
    

    So far, this only appears to happen when I am using MySQL. I think I read another post on StackOverflow where someone had a similar problem using .size with AR results and MySQL, and the solution was to always use .length on their AR results. I have tried modifying will_paginate to replace all instances of .size with .length, but alas it was not that simple, but I suspect that this or a similar issue is somehow affecting will_paginate.

    For the time being, I am using your find(:all) trick to hack around this.

提交回复
热议问题