Pi Horse
Pi Horse

Reputation: 2440

Cycle through values in an Ruby Array on a HTML page

I am fetching some rows from the database in my controller with this query :

@main = connection.execute("select code_ver, result from mastertest;")

Now in my html.erb, I am displaying the results in a table like this:

<% @level1.each do |row1| %>
<table id="tbl_main1" name="tbl_main1">
    <tr bgcolor="#D1D1D1">
        <td width="60%" <%= row1[0] %>></td>
        <td width="20%"><%= row1[2] %></td>
        <td width="20%"><%= row1[1] %></td> 
    </tr>
</table>

I am fetching a lot of rows here. But I want to show only say 15 results at once, and have some kind of buttons 'next' and 'previous' which would cycle through the results. How would I do that ?

Upvotes: 3

Views: 239

Answers (3)

brentmc79
brentmc79

Reputation: 2541

I'd suggest creating an Active Record model to represent your mastertest database table. Then, with the help of the will_paginate gem, you could do the following in your controller:

@mastertests = MasterTest.all.paginate(:page => params[:page], :per_page => 15)

And then in your view:

<% @mastertests.each do |mastertest| %>
  <td><%= mastertest.code_ver %></td>
  <td><%= mastertest.result %></td>
<% end %>
<%= will_paginate @mastertests %>

The will_paginate view helper will generate pagination links like [prev] [1] [2] [3] [next]. Take a look at the will_paginate gem on github for more options.

Upvotes: 1

Leo Correa
Leo Correa

Reputation: 19839

Take a look at this gem https://github.com/mislav/will_paginate

Will_paginate could be useful for what you are looking for.

There are other gems out there as well but I've found will_paginate to fulfill pagination needs.

Edit If you plan to paginate on an array which is what it seem you are doing, you could do:

require 'will_paginate/array'

and then your_array.paginate page: x, per_page: y

x would be the page you want to display and y is the number of items per page.

Upvotes: 2

ndbroadbent
ndbroadbent

Reputation: 13803

If you're using Rails 3, have a look at kaminari for pagination: https://github.com/amatsuda/kaminari. You are probably interested in the Paginating a generic Array object feature. However, keep in mind that this won't add offsets and limits to your SQL query.

Kaminari is widely considered better than will_paginate for Rails 3, since it takes advantage of Rails scopes and doesn't globally pollute objects.

Upvotes: 2

Related Questions