Reputation: 25
I want to do load data with load more button. I have implemented like this in posts/index.html.erb:
<div id="posts">
<h1>Posts</h1>
<%= render @posts %>
</div>
<div class="load-more-container">
<%= link_to "Load More", posts_index_path, class: "load-more" %>
</div>
Then _post.html.erb:
<div class="post">
<h2><%= post.title %></h2>
<p><%= post.body %></p>
</div>
Then index.js.erb:
$('#posts').append('<%= escape_javascript render(@posts) %>');
In posts_controller I wrote like this:
@@count=2
def index
if params[:id]
@posts = Post.where('id < ?', params[:id])
else
@posts = Post.limit(@@count)
end
@@count+=2
respond_to do |format|
format.html
format.js
end
end
Then in application.js:
$(document).ready(function () {
$('a.load-more').click(function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: $(this).attr('href'),
dataType: "script",
success: function () {
$('.load-more').show();
}
});
});
});
I am getting first 2 data:
Post1
Post2
load more
when clicking on load more I am getting like this:
Post1
Post2
Post1
Post2
Post3
Post4
but I want only:
Post1
Post2
Post3
Post4
Could anyone please help me. Thanks in advance.
Upvotes: 1
Views: 2527
Reputation: 532
In your controller, you replace
@posts = Post.limit(@@count)
=> @posts = Post.limit(2).offset(@@count - 2)
if you want load more 2 artices.
Upvotes: 0
Reputation: 2675
Since you are fetching all records everytime click on loadmore button, Dont append result and overwrite with html
$('#posts').html('<%= escape_javascript render(@posts) %>');
Upvotes: 1