How to using Jquery for render model in multi place in rails 6

153 Views Asked by At

I have issue when try using Jquery and Kaminari for render more model as below

  1. 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
  1. Have a partial for render post in _post.html.erb

  2. Render 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?

1

There are 1 best solutions below

1
rmlockerd On

All the embedded Ruby statements in an .html.erb file are interpreted at the time the page is first rendered. So, in your <script> block render @posts occurs at the point the HTML for the page is generated, not at the point the function is triggered. So, at that point @posts probably 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 @posts so that when home.js.erb runs,@posts actually contains the next set of records.