如何正确处理 Rails 4 中的远程链接?杰森

How do I properly handle a remote link to in Rails 4? JSON?

本文关键字:链接 杰森 程链接 正确处理 Rails      更新时间:2023-09-26

我有以下代码:

= link_to "#{icon('heart')} Props".html_safe, vote_picture_path(picture), class: 'tiny radius secondary button vote', method: :put, remote: true

这是在这里:

  # VOTE /pictures/1.json
  def vote
    respond_to do |format|
      if @picture.toggle_vote(current_user)
        format.json { render json: @picture }
      else
        format.json { render json: @picture }
      end
    end
  end

我正在尝试做的是通过以下方式更新图片上的总票数:

$ ->
  $(".vote").on "ajax:success", (e, data, status, xhr) ->
    vote_count_size = $(".vote-count .size").html()
    vote_count_size_integer = parseInt(vote_count_size)
    console.info data

然而,让我感到困惑的部分是 console.info 数据。它似乎从我无法说出的来源返回了一些东西。我正在编辑/pictures/show.json.jbuilder,但它不会影响来自数据的内容。我想返回一个包含数据中总票数的 json 结构,以便我可以从成功回调更新页面上的计数。

首先,你的respond_to块可以大幅重构:

  # VOTE /pictures/1.json
  respond_to :json
  def vote
     @picture.toggle_vote(current_user)
     respond_with @picture
  end

这应该为您的 @picture var 返回一个 JSON 对象。您必须详细说明您在console中获得的数据?如果您提供您收到的数据,这将是一个巨大的帮助!

你应该用一个javascript文件(vote.js.erb)来回应 在这个你可以混合JavaScript和ERB表达式来改变所需的页面元素:

$('.vote-count .size').html('<%=@picture.vote_count%> votes');

您的控制器如下所示:

# VOTE /pictures/1.js
def vote
  respond_to do |format|
    @picture.toggle_vote(current_user)
    format.js 
  end
end