2015-10-23 70 views
2

guys!我開始學習RAILS。 我有一個使用分頁的micropost列表。當我摧毀微博時,它會進入第一頁。但是當我銷燬微博時,它會重新加載當前頁面。如何在RAILS中用AJAX銷燬微博時重新加載當前頁面

這是我的代碼:

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 %> 

你有任何想法來處理這個問題?

+0

您需要重定向回家,但也傳遞頁面參數 – ediblecode

+0

在'destroy'操作中'params [:page]'是否返回正確的頁碼? – nsave

+0

@nsave它不返回頁碼,所以我不能重新加載右頁。 –

回答

1

嘗試page PARAM添加到您的刪除請求是這樣的:

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

感謝您的幫助。 :) –

+0

@KenyoKai,不客氣;) – nsave

1

我開始學習鋼軌

歡迎您!


簡單的解決方法:

#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 %>"); 
+1

感謝您的幫助。 –

+0

沒問題的傢伙,我更感興趣的是否*作品* :) –

相關問題