调用更新方法在阿贾克斯轨后更新分区索引视图? [英] update div in index view after calling update method in ajax in rails?

查看:101
本文介绍了调用更新方法在阿贾克斯轨后更新分区索引视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个帖子列表页,我用 AJAX 分页使用 will_paginate 和我有一个喜欢附近每一个职位按钮。如果用户点击Like按钮,然后我需要更新在我的表喜欢的数和我想的Like按钮切换到不喜欢

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. 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".

说,例如,如果我在帖子的第二页和我点击了Like按钮,我需要调用我的更新方法,我怎么可能带回了同一个页面,并使用AJAX更改按钮

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.

我可能做的,如果我的更新逻辑是相同的索引方法,但我怎么能替换内容的 index.html.erb 如果我的逻辑驻留在更新方法。

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.

请帮助我。谢谢你。

推荐答案

你的问题说:

说,例如,如果我在帖子的第二页和我点击了Like按钮,我需要调用我的更新方法,我怎么能带回同一页使用AJAX更改按钮。

让经过的步骤一一:

一个。为您自定义的方法创建一个路线在这里您可以更新它,它必须是一个 的路线,因为我们要发的帖子ID将被更新

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 '/update_post/:id' => "your_controller#update_post", as: :update_post

乙。创建链接:

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

℃。有一个的respond_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

Ð。更新您在update.js.erb链接

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

现在起的我们正在更新阿贾克斯你的链接和后你会留在同一个页面,你不会有担心分页的。欲了解更多信息,请参阅 用JavaScript在轨工作

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. For more information refer to Working with javascript in rails

这篇关于调用更新方法在阿贾克斯轨后更新分区索引视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆