[英]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.