user2492854
user2492854

Reputation: 401

Pagination for a generic search in rails 3

I have a million records in my database. I want to implement a generic search box with regex and the results should appear 50 per page . I want to implement pagination

class TweetsController<ApplicationController
  def query
    @tweets =Tweets.where("%query%=?", params[:search]).all
  end
end
<%= form_tag({controller: "tweets", action:"query" }, method: "get") do  %>
<%= label_tag(:search, "search for:") %>
<%= text_field_tag(:search) %>
<%= submit_tag("Search") %>
<% end %>

its actually a full text search. .For eg if i enter "apple" it should show results starting, ending, starting also anywer in d middle ,and it should show all the columns in the table.Any one Please help me . Thks in advance.

Upvotes: 0

Views: 1208

Answers (3)

Marek Lipka
Marek Lipka

Reputation: 51151

You can use will_paginate gem.

To do this, you first add

gem 'will_paginate'

to your Gemfile, then you run bundle. When you are done, you type in your controller:

class TweetsController < ApplicationController
  def query
    @tweets = Tweets.where("%query%=?", params[:search]).paginate(
      page: params[:page], per_page: 50)
  end
end

and in your view:

<%= will_paginate @tweets %>

to display pages links.

Upvotes: 0

Debadatt
Debadatt

Reputation: 6015

I think You have Tweet model as per your controller says TweetsController .

Use pagination for will_paginate(https://github.com/mislav/will_paginate)

And in controller change a little bit like

class TweetsController < ApplicationController
  def query

    @tweets = Tweet.where("field LIKE ?", "%#{params[:search]}%" ).paginate(
      page: params[:page], per_page: 50)
  end
end

In views

<%= will_paginate @tweets %>

Upvotes: 1

Jyothu
Jyothu

Reputation: 3144

Another good option is using Kaminari Gem

 def index
   @tweets = Tweet.where("%query%=?",params[:search]).page(params[:page]).per(params[:per])

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @tweets }
  end
end

You can simply configure default_per_page as you needed. Please read Configuring Kaminari

And in views simply use

 <%= paginate @tweets %>

Upvotes: 0

Related Questions