【问题标题】:How to reload current page when destroy a micropost with AJAX in RAILS在RAILS中使用AJAX销毁微博时如何重新加载当前页面
【发布时间】:2023-04-02 13:56:01
【问题描述】:

伙计们!我开始学习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 %>

你有什么想法来处理这个问题吗?

【问题讨论】:

  • 需要重定向到home还要传入page参数
  • params[:page]destroy 操作中是否返回正确的页码?
  • @nsave 它不是返回页码,所以我无法重新加载正确的页面。

标签: ruby-on-rails ruby ajax ruby-on-rails-3


【解决方案1】:

我开始学习RAILS

欢迎!


简单修复:

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

【讨论】:

  • 没问题,伙计,我更感兴趣的是它是否有效 :)
【解决方案2】:

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

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

【讨论】:

  • 感谢您的帮助。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-07
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 2011-03-22
相关资源
最近更新 更多