【问题标题】:update div in index view after calling update method in ajax in rails?在rails中调用ajax中的更新方法后更新索引视图中的div?
【发布时间】:2014-06-28 15:10:54
【问题描述】:

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

例如,如果我在帖子的第二页并单击“Like”按钮,我需要调用我的更新方法,我如何才能回到同一页面并使用 ajax 更改按钮.

如果我的更新逻辑在同一个索引方法中,我可能会这样做,但如果我的逻辑驻留在 update 方法中,我如何替换 index.html.erb 中的内容。

请帮助我。谢谢。

【问题讨论】:

  • 如果您不重定向它并通过 ajax 更新所有内容,那么您不会还在同一页面上吗?
  • 对不起,我听不懂。如果我点击like按钮,那么它会更新,更新方法的js响应将如何替换index.html.erb的按钮
  • 哦,我以为您是通过 ajax 更新它,顺便说一句,我认为您应该通过 ajax 请求更新它,因为这应该是正确的流程,否则您将不得不以某种方式调用分页,即使那样它只会显示您的正确页面而不是更新的问题。
  • 是的,我正在通过 Ajax 进行更新,但我仍然无法理解如何更改按钮。对不起,如果我不清楚。你能帮我一些代码示例吗?
  • 你能发布你在ajax调用中执行的代码

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


【解决方案1】:

你的问题是:

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

b.创建链接:

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

c。在你的方法中有一个respond_to block更新你的帖子:

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

【讨论】:

  • 非常感谢。我在想的是如何从 update.js.erb 更新索引视图。
  • 为什么要更新索引视图?这是一个 ajax 请求,因此用户将留在当前页面,因此在他/她的帖子中。
  • 好的,我明白了。谢谢。
猜你喜欢
  • 2016-09-13
  • 1970-01-01
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
  • 2017-09-30
  • 1970-01-01
  • 2013-10-11
  • 2014-11-29
相关资源
最近更新 更多