Search code examples
ruby-on-railspaginationwill-paginateruby-on-rails-2

will_paginate and acts_as_indexed produces odd pagination results


I'm implementing a search function by using acts_as_indexed along with will_paginate. I'm using Ruby 1.8.7 and Rails 2.3.11. No, I cannot upgrade Ruby as I'm using a shared host.

Regular use of the 'paginate' method yields expected results, however when using 'paginate_search' (acts_as_indexed pagination method), I get weird results:

-The wines are all retrieved from the database (I looked at the log and the query looks good)
-It's the pagination that screws up, yielding inconsistent 'per-page' results

Assuming a search result of 3 objects:

Set per-page to 1, get 18 pages all without results except for pages 4, 12 and 18
Set per-page to 2, get 9 pages all without results except for pages 2, 6 and 9 (see a pattern here?)
Set per-page to 3, get 6 pages all without results except for pages 2, 4 and 6
- All of the above patterns yield 1 result per result page

So on and so forth...it seems there's some funky math going on but I don't know where or why.


Solution

  • OK well I figured out a way around the issue. Essentially I was putting in a condition into the search function which was just screwing it up somehow. It was a simple "stock > 0" string and I have no idea why it messed with acts_as_indexed but whatever. The workaround was to add a search attribute called 'stocked'. Any product that had stock would be searchable by the term 'stocked' and any wine that didn't have stock would not have that attribute. Instead of putting in a :conditions parameter into the search method I just appended the ' stocked' string to the search string when necessary. It works now. Code snippets below:

    Wine.rb

    # ... = indicates other attributes
    acts_as_indexed :fields => [..., :stock_search]
    
    def stock_search
        'stocked' if stock > 0
    end
    

    wines_controller.rb

    srch = "#{ safe_tags * " " }#{ ' stocked' if params[:search_all].nil? }"
    @wines = Wine.paginate_search(srch, :page => pg, :per_page => 10, :include => [{:awards => [:medal, :competition]}, {:reviews => :reviewer}])
    

    So to recap:

    This works: Wine.paginate_search("cabernet stocked", :page => pg, :per_page => 10)

    This doesn't: Wine.paginate_search("cabernet", :conditions => "stock > 0", :page => pg, :per_page => 10) ... well technically the search works, but the pagination doesn't.

    Hope this helps someone if they encounter the same issue.