[英]update div in index view after calling update method in ajax in rails?
I have a page with list of posts and I use ajax
for pagination using will_paginate
and I have a "Like" button
near by each post. 我有一个包含帖子列表的页面,我使用
ajax
通过will_paginate
进行分页,并且每个帖子附近都有一个"Like" button
。 If the user clicks the "Like" button then I need to update
the count of likes in my table and I want to change the "Like" button to "Dislike"
. 如果用户单击“喜欢”按钮,那么我需要
update
表中的“喜欢”次数,并且我想将“喜欢”按钮更改为"Dislike"
。
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. 假设例如,如果我在帖子的第二页中,然后单击“赞”按钮,则需要调用我的更新方法,如何才能回到同一页面并使用ajax更改按钮。
I could possibly do if my update logic is in the same index method but how could I replace the content in the index.html.erb
if my logic resides in the update
method. 如果我的更新逻辑位于相同的索引方法中,我可能会做,但是如果我的逻辑位于
update
方法中,该如何替换index.html.erb
的内容。
Please help me. 请帮我。 Thanks.
谢谢。
Your question says: 您的问题是:
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.
Lets go through the steps one by one: 让我们一步一步地完成以下步骤:
a. 一种。 Create a route for your custom method where you'll update it and it has to be a
post
route since we want to send the post id which is to be updated 为您的自定义方法创建一条路由 ,您将在其中对其进行更新,并且它必须是
post
路由,因为我们要发送要更新的发布ID
post '/update_post/:id' => "your_controller#update_post", as: :update_post
b. 湾 Create a link:
创建一个链接:
<%= link_to "Like", update_post_path(post.id),id: "post_#{post.id}",method: :post %>
c. C。 Have a respond_to block in your method and update your post:
在您的方法中添加一个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. d。 Update your link in update.js.erb:
更新update.js.erb中的链接 :
$("#post_<%= @post.id %>").text("Dislike");
Now since we are updating your link and post by ajax you will remain at same page and you wont have to worry about pagination . 现在,由于我们正在更新您的链接并通过ajax发布,因此您将停留在同一页面上,而不必担心分页 。 For more information refer to
Working with javascript in rails
有关更多信息,请参阅
Working with javascript in rails
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.