Adding pagination to index.html.erb in Ruby on Rails - Easy Question - ruby-on-rails

I am new to rails so go easy. I have built my first blog and would like to set it up such that in the <% post.each do |post| %> render of the posts, I would like it to work such that it only displays 10 posts and then has a link to view the next 10.
I am hoping this is an easy question. Let me know if you would like me to post any code.

You should use the gem will_paginate.
The installation and usage is really easy: https://github.com/mislav/will_paginate/wiki/installation
Example usage: http://github.com/mislav/will_paginate

will_paginate is definitely the way to go, I just thought I'd add a link to a railscasts will_paginate video showing you how to use it since sometimes that can be an easier way to learn the basics than reading documentation. Plus you'll learn a brief history on how pagination used to be done when it was an included part of Rails (it was slower and more cumbersome). The old classic pagination has been moved out into it's own plugin too, but it's only recommended if you were already using it when you upgraded Rails to a version where they took it out.
Railscasts has a ton of other great videos that you might find helpful. For example, once you get more advanced you might want to try ajax pagination

Check out the will_paginate Gem.
It’s very easy to do pagination on ActiveRecord models:
#posts = Post.paginate :page => params[:page], :order => 'created_at DESC'
In the view, page links can be rendered with a single view helper:
<%= will_paginate #posts %>

I've got problems using "will_paginate", installing the GEM then unistalling... a REAL PROBLEM! So I decide to program the pagination on RoR, it was not difficult so I wanted to share what I did:
Controller:
def index
#how many register per page i want to show
#b = 30
#params via GET from URL
a = params[:page].to_i
#first register per page
a1 = params[:page].to_i * #b
#the query can be easy...
#callcenters = Income.all(:joins => "LEFT JOIN radcheck ON radcheck.id = incomes.radcheck_id", :order => "created_at DESC",:limit => "#{a1},#{#b}", :select => "radcheck.username as clave,caller_id, created_at, value")
#I need to know how many pages somehow
#registrostotales = Income.all(:joins => "LEFT JOIN radcheck ON radcheck.id = incomes.radcheck_id", :select => "radcheck.username as clave,caller_id, created_at, value").count
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #callcenters }
end
end
View:
...
Total de registros: <%= numero = #registrostotales %><br/><br/>
<!-- total pages -->
<% pages = #registrostotales / #b %>
<!-- the last page -->
<% if pages % #b > 0 %><% pages = pages + 1 %><% end %>
Paginas:
<% (0..(pages-1)).each do |i| %>
<!-- href or link_to, http://xxxxxxxx/yyyy?page=i -->
<%= link_to i+1, :action => "index", :controller => "callcenters", :page => i %>
<% end %>
<!-- the view.. -->
<table>
<tr>
<th>#</th>
<th>Teléfono (ID)</th>
<th>Zona</th>
</tr>
<% #callcenters.each do |callcenter| %>
<tr>
<td><%= numero - params[:page].to_i * 30 %><% numero = numero - 1 %></td>
<td><%= callcenter.caller_id %></td>
<td><%= Node.first(:conditions => {:calling_id => callcenter.caller_id}).description %></td>
</tr>
<% end %>
</table>
I hope this helps to someone!

We can do this with ease by using 'will_paginate-bootstrap' gem.
To continue firstly you add a line to the gem file as,
gem 'will_paginate-bootstrap'.
Now run bundle install.
In the controller, you will be using like #post = Post.all to get the
contents from models.
Instead use this
#post = Post.paginate(:page=>params[:page],per_page:5)
Here in the above line per_page field is to specify how many records you need
in a page.
In index.html.erb
At the end of the code i.e before ending the body tag
Add this,
<%= will_paginate #post,renderer: BootstrapPagination::Rails %>
Note: I thought Post as modal and post as variable declared in the controller.
Just go with your variables.

You can use the kaminari gem.
Very ease to use and highly customization friendly.

Adding pagination to a Ruby on Rails app
To add pagination to your Ruby on Rails app, you have to modify the following files:
Gemfile:
gem 'will_paginate', '~> 3.1.0'
gem 'will_paginate-bootstrap'
Areas controller --> index
#areas = Area.pagination_request(params[:page])
index.html.erb
<%= will_paginate #areas, renderer: BootstrapPagination::Rails %>
Model file:
def self.pagination_request(page)
paginate :per_page => 10, :page => page
end

Or, small, swifd & actively maintained: Pagy

Related

will_paginate with 2 list on the same view

I have too list #comments and #eval in the same view. If I go to the page 2 in the #eval, the comments page go to the page 2 as well, there is a simple way to do this in the separated way?
You can define a custom parameter name (param_name) for each pagination link group and differentiate the page number by that:
# in view
<%= will_paginate #foos, :param_name => :foo_page %>
<%= will_paginate #bars, :param_name => :bar_page %>
# in controller
#foo = Foo.paginate(page: params[:foo_page])
#bar = Bar.paginate(page: params[:bar_page])
Find the list of possible options in the source code of the gem: https://github.com/mislav/will_paginate/blob/v3.0.5/lib/will_paginate/view_helpers.rb#L46

How to make partial_counter work with pagination

I have a blogging application in which User has_many posts. I am using pagination with Booststrap. How can I make the partial_count method work with pagination? Currently, the count resets on every page instead of carrying over across pages.
posts_controller.rb
def index
#posts = Post.order("created_at desc").paginate(page: params[:page], :per_page => 12)
end
views/posts/index.html.erb
<%= render #posts %>
<%= will_paginate %>
views/posts/_post.html.erb
<%= post_counter +1%>
<%= post.name %>
The counter works fine on the first page. However, all subsequent pages also start with "1". How can I make subsequent pages start with (number of pages * 12 + 1) instead?
Thanks for your feedback!
Use #posts.offset to get the proper counter initialisation.

Get most commented objects

I'm using acts_as_commentable_with_threading gem to make users able to comment my blog posts.
What I want to do now is to display most commented posts but I have no idea how to query them (and as far as I know, the gem not provides such method). Can you write me some tips or ideas how to achieve something like that?
Here is a method that I use to return the top users that have posted the most items. It may help you with your issue. I put this in the Application Helper because it is part of my side navigation bar and will be used on every page in the web application.
def top_posters
User.all(:select => "users.*, COUNT(user_id) as post_count",
:joins => "LEFT JOIN posts AS posts ON posts.user_id = users.id",
:group => "posts.user_id",
:order => "post_count DESC",
:limit => 5)
end
In my view, I have
<% top = top_posters() %>
<% for t in top %>
<li><%= link_to t.username, user_path(t) %>
(<%= t.posts.public_posts.count %>)</li>
<% end %>
For Rails 4+
You should use something like this:
Article.select("articles.*, COUNT(commentable_id) as comments_count")
.joins("LEFT JOIN comments AS comments ON comments.commentable_id = articles.id")
.group("comments.commentable_id")
.order("comments_count DESC")
.where("commentable_type = 'Article'")
.limit(5)

Rails 3 & Kaminari pagination problem

Ok so I have decided to use Kaminari for pagination in a rails 3 project. I have followed the video from RailsCasts http://railscasts.com/episodes/254-pagination-with-kaminari
All goes well up until the point or running the server.
controllers/stories_controller.rb
def index
#stories = Story.all
#pages = Story.page(params[:page]).per(3)
#stories = Story.search(params[:search])
end
views/stories/index.html.erb
<%= paginate #pages %>
When i start the server the index page in question displays all the stories from the DB and renders the pagination view showing (1 2 Next > Last »). What am I missing to get the pagination working?
I still can not understand your code. Why do you assign Story.all to #stories in the 1st line and overwrite the variable in the 3rd line?
Anyways, #stories will display "all the stories from the DB" because you're not calling the pagination method (.per) on #stories. The pagination links will show you the paginated counts because you're calling per method on #page variable and passing it to the helper.
I mean, you need to call .per on the relation before passing it to <%= paginate %> helper.
It's quite simple.
I guess you want to get results from your search, right?
Try
#stories = Story.search(params[:search]).page(params[:page]).per(3)
and something like:
<% #stories.each do |story| %>
<%= render story %>
<% end %>
<%= paginate #stories %>
in your view

Using Websolr with Heroku to do full text search

Hi I am having trouble trying to figure out how to implement a search form globally across my application. I have a series of posts that need to be searchable by users that are signed in and not signed in. I have added this code in my post model:
searchable do
text :content, :default_boost => 2
text :body, :default_boost => 1.5
end
However, I do not know where to go from there to create a search field across all pages and make it show the results I need. I am new to rails and would be happy to post more information if someone is willing to help me out.
First, you should add your search field like explained in this railscast: http://railscasts.com/episodes/37-simple-search-form
Since your search isn't specific to a particular model, use a generic controller name instead of ProjectsController though.
Then, you should replace the ActiveRecord finder by the use of the Sunspot DSL.
Here is an sample code to help get you started:
page = #page = params[:page] && params[:page].to_i || 1
#search = Sunspot.search(Realty) do # search_ids
per_page = params[:per_page] && params[:per_page].to_i || 10
# not adapted to your case
with(:equipments).all_of params['equip'].split(' ') if params['equip']
case params[:sort]
when "average_rating"
order_by :average_rating, :desc
when "type"
order_by :type, :asc
end
paginate :page => page, :per_page => per_page
# other criteria...
end
In your view, you can then iterate through #search.results
<%= will_paginate #search.results %>
<% #search.results.each do |hit| %>
<%# 'path' contains the stored polymorphic_path of each model object #%>
<% link_to hit.stored('path') do %>
<p><%= hit.stored('content') %></p>
<% end %>
<% end %>
Last, using WebSolR instead of a standard SolR server is quite simple, you can follow the setup instructions at https://github.com/onemorecloud/websolr-rails.
Edit:
As Nick commented, you should totally go to http://docs.heroku.com/websolr.
Thanks Nick !

Resources