后控制器索引为
df['Laptimes'].time()
我的@post部分是
<% if params[:topic_id].present? %>
<div class="new_post">
<%provide(:page_title,@topic.topic) %>
<h2><%= @topic.topic %></h2>
<%= link_to "Add Post",new_topic_post_path,remote: true,id: "post"%> .
<br>
<% else %>
<h1>Posts</h1>
<%provide(:page_title,"ALL") %>
<% end %>
<div class="row" id="posts">
<%= render @posts %>
</div>
<%= will_paginate @posts ,renderer: BootstrapPagination::Rails %>
</div>
在Post Controller中创建操作如下
<div class="col-sm-6 col-lg-4" id="<%=post.id%>">
<div class="card">
<div class="card-topper">
<%=image_tag post.image.url(:medium) %>
</div>
<div class="card-block">
h4 class="card-title"><%= link_to post.title, topic_post_path(topic_id: post.topic_id,id: post.id),remote: true %><%= "(#{post.topic.topic})" %><br></h4>
<p class="card-text" id="unused"><%= truncate(post.description,length:30) %></p>
<%= "Avg.rate:#{post.ratings.average(:rate).to_f.round(2)}"%><br>
<%= "#{post.comments_count} comments" %><br>
<% if ReadStatus.where(user_id: current_user.id,post_id: post.id).blank? %>
<%= link_to 'Read',topic_post_path(topic_id: post.topic_id,id: post.id),class: 'btn btn-read read' %>
<% else %>
<%= link_to 'Continue Reading',topic_post_path(topic_id: post.topic,id: post), class: 'btn btn-read read'%>
<% end %>
</div>
我的create.js是
class PostsController < ApplicationController
protect_from_forgery
before_action :authenticate_user!
before_action :set_topic
before_action :set_post, only: [:show, :edit, :destroy, :update]
respond_to :html,:js
def create
@post = @topic.posts.new(post_params)
@post.user=current_user
if @post.save
flash[:notice] = "Post sent Successfully"
respond_to do |format|
format.html {redirect_to topic_post_path(id: @post.id)}
format.js
end
else
render 'new'
end
end
当我尝试在我的帖子索引中添加新的帖子时,例如enter image description here
新帖子将添加到我创建的同一页面。在这里,我将我的每页设置为2,但是新帖子将添加到该页面中已经有两个帖子的同一页面。但是当我刷新它时,索引以正确的顺序加载。如何在不刷新页面的情况下正确获得分页
答案 0 :(得分:0)
首先,我建议您停止从视图中触发sql查询,因为它会中断MVC的流程,并且也会增加呈现时间。
解决您所面临的问题: 您正在使用prepend,它将在第2个空格中添加第3个帖子,如果您要重复创建另一个帖子,它将继续添加。
我建议您在create方法中获取@posts
if @post.save
#add line to fetch posts in the same order you're fetching on index page
#example:
@posts = Post.order(created_at: :desc).paginate(:page => 1, :per_page => 2)
end
和create.js.erb
$('#posts').empty();
<% @posts.each do |post| %>
$('#posts').append('<%= j render post %>');
<% end %>