Showing posts with label show items per page in ajax. Show all posts
Showing posts with label show items per page in ajax. Show all posts

Thursday, November 12, 2009

Ruby on Rails : Show items per page in Ajax

In views.rhtml
<script language = "javascript">
function check(pagenum, totalpage){
for(var i=0;i<=totalpage;i++){
if(i==pagenum)
document.getElementById('page'+pagenum).style.border='1px solid #000000';
else
document.getElementById('page'+i).style.border='0px solid #000000';
}
}
</script>

<%= javascript_include_tag "prototype" %>
<%
@articles = Article.find(:all, :limit => 10)
@allarticles = Article.find(:all)
@total = @allarticles.length/10

for x in 0..@total
@num = x+1
%>
<span id="page<%=x%>" onclick="check(<%=x%>,<%=@total%>)">
<%= link_to_remote @num, :url => { :action => "articles_per_page", :id => x },
:update => "article_list" %>
</span>
<% end %>

<div id = 'article_list'>
<%= render :partial => 'article', :collection => @articles %>
</div>

In partial page, _article.rhtml
Title: <%= article.title %><br>
Author: <%= article.author %>
<hr>

In controller.rb
def articles_per_page
@show = ((params[:id].to_i)*10)
@articles = Article.find(:all, :offset => @show, :limit => 10)
render :partial => 'article', :collection => @articles
end
** :offset, starting id to show per page
** :limit, limit data showing

Class Pagination : http://rails.rubyonrails.org/classes/ActionController/Pagination/Paginator/Page.html#M000158
Prototype Helper : http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html#M001645
Other source : http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/remote_form_for