Search code examples
ruby-on-railspaginationkaminari

Paginating search results with Kaminari


I've been trying to do this for the last 2 hours with no success, I'm sure it's something really simple :)

So, I have form where users can search things based on some keywords. Here's the form code:

<%= form_tag search_by_description_path,:method => "get" do %>
        <div class="column span-3">
            <label>Search</label>
        </div>

        <div class="column span-5">
            <input type="text" name="search_keywords" id="search_keywords"/>
        </div>

        <div class="column span-6">
            <%= collection_select :category,:id,Category.all,:id,:name,:include_blank => "Everything" %>
        </div>

        <div class="column span-3">
            <%= submit_tag "search" %>
        </div>

    <% end %>

I have this in the routes.rb:

get "search_by_description" => "search#search_by_description",:as => "search_by_description"

I have this in the controller:

def search_by_description
    category    = params[:category_id]
    kw          = params[:search_keywords]
    @results = Posts.where("description LIKE ?","%#{kw}%").page(params[:page])
end

Ignore the fact that I'm not keeping track of category_id. In my view I have this:

<%= render "results",:locals => {:results => @results} %>
<%= paginate(@results) %>

The problem is, the when I go to the second page, I don't see anything displayed. Looking in the console, I noticed something that for the 1st page, the following SQL gets generated:

 SELECT "posts".* FROM "posts" WHERE (description LIKE '%lorem%') ORDER BY id LIMIT 25 OF
SELECT COUNT(*) FROM "posts" WHERE (description LIKE '%lorem%')

while for the second only:

SELECT COUNT(*) FROM "posts" WHERE (description LIKE '%lorem%') LIMIT 25 OFFSET 25

Please give me some suggestions, I don't want to resort to writing my own pagination :)


Solution

  • The root cause of this problem is ActiveRecord 3.0's bug, which will be fixed in ActiveRecord 3.1 https://github.com/rails/rails/commit/d5994ee https://github.com/rails/rails/commit/28c73f0

    And I did a monkeypatch on Kaminari to work with ActiveRecord 3.0 https://github.com/amatsuda/kaminari/blob/9d0eebe38e2a22fb8100e491a6d94839d76c868f/lib/kaminari/models/active_record_relation_methods.rb#L7-11

    In short, updating your Kaminari gem to the newest one will fix your problem. Thanks!