尝试通过 AJAX 开机自检时出现 Rails"无路由匹配"错误



我正在构建一个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"}

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

在我的控制器中,我没有定义@question。这不是问题,直到我将请求转换为 ajax 并需要变量在我的 javascript 中呈现部分。

我添加了

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

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

在您的控制器中,您有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)方法不能。

最新更新