簡體   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