尝试通过AJAX POST时,Rails“无路由匹配”错误

时间:2013-09-21 02:35:23

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

我正在构建一个rails应用程序,允许用户对嵌套的问题和答案进行投票:

此代码旨在让用户投票给答案:

<%= link_to raw('<i class="icon-2x icon-chevron-up"></i>'), vote_question_answer_path(@question, answer, :type => :up), :method => :post %>

但是这段代码应该通过ajax执行相同的操作:

<%= link_to raw('<i class="icon-2x icon-chevron-up"></i>'), vote_question_answer_path(@question, answer, :type => :up), :remote => true, :method => :post %>

正确记录投票,但随后出现以下错误:

ActionController::RoutingError at /questions/fugiat-nulla-blue-bottle-raw-denim-fap-sint-butcher-ethical-cosby-sweater-thundercats-distillery-laboris-tofu/answers/6/vote=========================================================================================================================================================================> No route matches {:action=>"vote", :controller=>"answers", :type=>:up, :question_id=>nil, :id=>#<Answer id: 6, body: "Ullamco Pinterest food truck incididunt trust fund,...", user_id: 1, question_id: 10, created_at: "2013-09-10 22:20:40", updated_at: "2013-09-10 22:20:40">}app/views/shared/_vote_answer_arrows.html.erb, line 6

我很困惑 - 不是两张贴在同一条路线上的吗?为什么一个工作而另一个发出路由错误?

我认为问题与嵌套路由有关,因为我的问题代码几乎相同,而AJAX路由在那里工作。

编辑:根据要求,以下是相关路线:

resources :questions do
  member { post :vote }
  resources :answers do
    member { post :vote }
  end
end

并且respond_to做|格式|

respond_to do |format|
  format.html{ redirect_to :back, :flash => { :success => 'Thank you for voting!' }}
  format.js {}
end

以下是来自firebug的AJAX错误消息/ URL:

"NetworkError: 500 Internal Server Error - http://localhost:3000/questions/fugiat-nulla-blue-bottle-raw-denim-fap-sint-butcher-ethical-cosby-sweater-thundercats-distillery-laboris-tofu/answers/5/vote?type=down"

这是来自firebug的AJAX参数(这对我来说看起来非常错误,所以我不确定它是问题的根源还是我不熟悉firebug:

type    down

这是来自服务器输出的成功的非AJAX请求参数:

Parameters: {"authenticity_token"=>"X3Dg3TSZ8blMNTT1Zce2R0A1rtZI93ViFJNsjOP145w=", "type"=>"up", "question_id"=>"fugiat-nulla-blue-bottle-raw-denim-fap-sint-butcher-ethical-cosby-sweater-thundercats-distillery-laboris-tofu", "id"=>"3"}

2 个答案:

答案 0 :(得分:1)

正如我在上面的评论中所提到的,这是一个简单的控制器问题。

在我的控制器中,我没有定义@question。在我将请求转换为ajax并且需要变量来渲染我的javascript中的部分之前,这不是问题。

我添加了

@question = Question.find(params[:question_id])

到控制器,它解决了问题。

答案 1 :(得分:-1)

在您的控制器中,您是否有respond_to do |format|阻止?

你应该有类似......

respond_to do |format|
  if something_saves or whatever
    format.html { redirect_to random_path, notice: 'Vote was casted.' }
    format.json { render :json => { :voteCasted => true } }
  else
    format.html { render :nothing }
  end
end

主线有......

format.json { render :json => { :voteCasted => true } }

目前听起来你似乎缺少对JSON格式的回应。这就是为什么HTML版本工作正常而AJAX(JSON)方法不正常的原因。