繁体   English   中英

在RAILS中使用AJAX销毁微信时,如何重新加载当前页面

[英]How to reload current page when destroy a micropost with AJAX in RAILS

伙计们! 我开始学习铁路。 我有使用分页的微信列表。 当我销毁微帖时,它会转到第一页。 但是我想当我销毁微帖时,它将重新加载当前页面。

这是我的代码:

static_pages_controller.rb

def home
    return unless logged_in?
    @micropost  = current_user.microposts.build
    @feed_items = current_user.feed.paginate(page: params[:page])
end

microposts_controller.rb

def destroy
    @micropost.destroy
    @feed_items = current_user.feed.paginate(page: params[:page])
    respond_to do |format|
      format.html { redirect_to request.referrer || root_url }
      format.js
    end
  end

destroy.js.erb

$("#microposts").html("<%= escape_javascript(render('shared/feed')) %>");

_microposts.html.erb

<% if current_user?(micropost.user) %>
      <%= link_to "Delete", micropost, remote: true,
                                       method: :delete,
                                       data: { confirm: "You sure?" } %>
    <% end %>

_micropost.html.erb

<ol class="microposts" id="microposts_profile">
  <%= render @microposts %>
</ol>
<%= will_paginate @microposts %>

您有解决这个问题的想法吗?

我开始学习铁路

欢迎!


简单修复:

#app/views/microposts/destroy.js.erb
location.reload(); // Reloads current page (the :page param should be predefined from the URL)

正确的解决方法:

#app/views/microposts/index.html.erb
<%= render @microposts %>
<%= will_paginate @microposts %>

#app/views/microposts/_micropost.html.erb
<%= link_to "Delete", micropost_path(micropost, page: params[:page]), remote: true, method: :delete, data: {confirm: "You sure?"} if current_user? == micrpost.user %>

#app/controllers/microposts_controller.rb
class MicropostsController < ApplicationController
   before_filter :authenticate
   respond_to :js, :html

   def index
      @microposts = current_user.feed.paginate
   end

   def destroy
      @micropost = Micropost.find params[:id]          
      @microposts = current_user.feed.paginate(page: params[:page]) if @micropost.destroy
   end

   private

   def authenticate
      return unless logged_in?
   end
end

这将使您可以更新以下内容:

#app/views/microposts/destroy.js.erb
$("#microposts").html("<%=j render @microposts %>");

尝试将page参数添加到您的删除请求中,如下所示:

<% if current_user?(micropost.user) %>
  <%= link_to "Delete", micropost_path(micropost, page: params[:page]),
                                   remote: true,
                                   method: :delete,
                                   data: { confirm: "You sure?" } %>
<% end %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM