繁体   English   中英

在导轨中的ajax中调用更新方法后,在索引视图中更新div?

[英]update div in index view after calling update method in ajax in rails?

我有一个包含帖子列表的页面,我使用ajax通过will_paginate进行分页,并且每个帖子附近都有一个"Like" button 如果用户单击“喜欢”按钮,那么我需要update表中的“喜欢”次数,并且我想将“喜欢”按钮更改为"Dislike"

假设例如,如果我在帖子的第二页中,然后单击“赞”按钮,则需要调用我的更新方法,如何才能回到同一页面并使用ajax更改按钮。

如果我的更新逻辑位于相同的索引方法中,我可能会做,但是如果我的逻辑位于update方法中,该如何替换index.html.erb的内容。

请帮我。 谢谢。

您的问题是:

Say, for example if I am in the second page of the post and I click on the "Like" button I would need to call my update method and how could I bring back to the same page and change the button using ajax.

让我们一步一步地完成以下步骤:

一种。 为您的自定义方法创建一条路由 ,您将在其中对其进行更新,并且它必须是post路由,因为我们要发送要更新的发布ID

post '/update_post/:id' => "your_controller#update_post", as: :update_post

创建一个链接:

<%= link_to "Like", update_post_path(post.id),id: "post_#{post.id}",method: :post %>

C。 在您的方法中添加一个response_to块更新您的帖子:

def update_post
  @post = Post.find(params[:id])
  # update your post here
  respond_to do |format|
    format.js{} #this will allow you to have update_post.js.erb in your view
  end
end

d。 更新update.js.erb中的链接

$("#post_<%= @post.id %>").text("Dislike");

现在,由于我们正在更新您的链接并通过ajax发布,因此您将停留在同一页面上,而不必担心分页 有关更多信息,请参阅Working with javascript in rails

暂无
暂无

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

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