I have issue when try using Jquery and Kaminari for render more model as below
- Pagnigation Post model in PageController
def home
if "default" == @tab_id || "PostForYou" == @tab_id
@buffers = Post.all.sort_by {|post| cal_post_hot_point(post)}.reverse
@buffers = Post.where("created_at >= ?", 1.week.ago.utc)
@posts = Kaminari.paginate_array(@buffers).page(params[:page]).per(10)
end
end
Have a partial for render post in
_post.html.erbRender this partial in Home page:
<% if @posts.present? %>
<div id="home_infinite_scroll">
<%= render @posts %>
</div>
<div class="home_pagination_button" id="home_pagination">
<%= link_to_next_page(@posts, 'Next', remote: true, :onclick => "render_partial();") %>
</div>
<script>
function render_partial(){
// Append new data
$("<%=j render @posts %>").appendTo($("#home_infinite_scroll"));
// Update pagination link
<% if @posts.last_page? %>
$('#home_pagination').html("<a>End</a>");
<% else %>
$('#home_pagination').html("<%=j link_to_next_page(@posts, 'Next', :remote => true, :onclick => "render_partial();") %>");
<% end %>
}
</script>
<% end %>
Issue: when I click in "Next" button, only 10 first posts repeated. But, If I create home.js.erb and put script code in it, it will work.
I don't want to create new js file in each time need to render post. Do anyone have a solution?
All the embedded Ruby statements in an
.html.erbfile are interpreted at the time the page is first rendered. So, in your<script>blockrender @postsoccurs at the point the HTML for the page is generated, not at the point the function is triggered. So, at that point@postsprobably has the first 10 records. The script is then just static JS, and each time the button is clicked the Javascript dutifully appends it to the div.The right way to do it is the way you are trying to avoid (placing the JS in
home.js.erb). The reason that works is that when the user clicks the button, it performs an AJAX call (remote: true) back to your application, which then hits your controller. Your controller then (presumably) loads the next page of records into@postsso that whenhome.js.erbruns,@postsactually contains the next set of records.