【问题标题】:json data not being passed in Railsjson数据未在Rails中传递
【发布时间】:2014-11-19 18:59:07
【问题描述】:

我正在尝试使用 Rails 4 进行一个非常简单的 ajax 调用,但没有正确检索到 json 响应。

这是脚本:

$(document).on "submit", "form[name=upvote-form]", ->
  form = $(this)
  $.post "/vote", $(this).serialize(), (data) ->
    if data["status"] is true
      form.find("input").addClass "disabled"
      $("#vote-count-".concat(form.find("#question_id").attr("value"))).html data["votes"]
    else

    return

  return

alert(data['votes'])undefined,这让我试图找出问题所在。

然后在控制台中我可以看到:

ArgumentError (Nil location provided. Can't build URI.):
  app/controllers/vote_controller.rb:8:in `vote'

这是有问题的方法:

class VoteController < ApplicationController

    def vote
        question_id = params[:question][:id]
        user_id = current_user.id
        vote = Vote.where(["question_id = :q", { q: question_id }]).where(["user_id = :u", { u: user_id }]).take
        respond_to do |format|
            if vote.nil?
                @vote = Vote.new
                @vote.question = Question.find question_id
                @vote.user = User.find user_id
                @vote.save
                votes = Vote.where(["question_id = :q", { q: question_id }]).count
                format.json { render :json => { status: true, votes: votes } }
            else
                format.json { render :json => { status: false } }
            end
        end
    end
end

有什么线索吗?我能做什么?

【问题讨论】:

  • 我认为这是因为您没有将资源传递给 respond_with 并且它无法确定位置。尝试将其更改为respond_to 或将:location 选项传递给respond_withReference

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


【解决方案1】:

respond_with 旨在与资源一起使用。示例

def show
  @vote = Vote.find params[:id]
  respond_with(@vote)
end

在您的情况下,您需要使用respond_to 方法

def vote
  # stuff
  respond_to do |format|
    if vote.nil?
      # stuff
      format.json { render json: { status: true, votes: votes } }
    else
      # other stuff
    end
  end
end

【讨论】:

  • 如果我经常这样做,我会得到 (ActionController::UnknownFormat (ActionController::UnknownFormat): app/controllers/vote_controller.rb:7:in 'vote')
  • 好的,我刚刚上传了
  • 我可以看到一个非常奇怪的行为。大多数情况下,成功发布功能不会执行(基本上它会禁用支持按钮并更新投票计数),但有时当我点击支持按钮时它会起作用!
  • 该错误是由于对 else 条件没有适当的响应造成的。如果投票不是零,应该怎么办?
  • 没什么,else 条件永远不会被执行,因为如果用户尝试对该项目进行投票,upvote 按钮将被禁用
猜你喜欢
  • 2014-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多