Rails:找不到ID为的#controller

时间:2011-12-01 06:32:25

标签: ruby-on-rails ruby controller

提交答案时,我收到此错误:

ActiveRecord::RecordNotFound (Couldn't find Question with ID=answer):
  app/controllers/questions_controller.rb:6:in `show'

根据我的理解,我或者从表单或者传递参数时出错了 没有在我的控制器中正确定义它。

非常感谢帮助找到这个错误,提前谢谢!

Questions_Controller:

class QuestionsController < ApplicationController
  def index
  end

  def show
      @question = Question.find(params[:id])
      @choices = @question.choices
  end

  def answer
      @choice = Choice.find(:first, :conditions => { :id => params[:id] })
      @answer = Answer.create(:question_id => @choice.question_id, :choice_id => @choice.id)

      if Question.last == @choice.question
        render :action => "thank_you"
      else
        question = Question.find(:first, :conditions => { :position => (@choice.question.position + 1) })
        redirect_to question_path(:id => question.id)
      end
   end
end

views / questions / show.html.erb:

<div data-role="content">
  <div align="center">
    <h3><%= @question.question %></h3>
  </div>
  <br><br>
  <ul data-role="listview">
    <% @choices.each_with_index do |c, i| %>
      <% i = i + 1 %>
      <li data-theme="c">
        <%= link_to "#{i}. #{c.choice}", answer_questions_path(:id => c.id) %>
      </li>
    <% end %>
  </ul>
</div>

:: EDIT ::

当我尝试选择一个选项&amp;在第一个问题上提交答案。

Started GET "/questions/1" for 127.0.0.1 at Thu Dec 01 01:38:36 -0500 2011
  Processing by QuestionsController#show as 
  Parameters: {"id"=>"1"}
  SQL (0.6ms)   SELECT name
 FROM sqlite_master
 WHERE type = 'table' AND NOT name = 'sqlite_sequence'
  Question Load (0.3ms)  SELECT "questions".* FROM "questions" WHERE "questions"."id" = 1 LIMIT 1
  Choice Load (10.8ms)  SELECT "choices".* FROM "choices" WHERE ("choices".question_id = 1)
Rendered questions/show.html.erb within layouts/application (28.8ms)
Completed 200 OK in 424ms (Views: 118.0ms | ActiveRecord: 11.6ms)


Started GET "/questions/answer?id=1" for 127.0.0.1 at Thu Dec 01 01:38:38 -0500 2011
  Processing by QuestionsController#show as 
  Parameters: {"id"=>"answer"}
  Question Load (0.1ms)  SELECT "questions".* FROM "questions" WHERE "questions"."id" = 0 LIMIT 1
Completed   in 10ms

ActiveRecord::RecordNotFound (Couldn't find Question with ID=answer):
  app/controllers/questions_controller.rb:6:in `show'

希望这有帮助。

1 个答案:

答案 0 :(得分:2)

我最好的猜测是你没有正确设置路线。假设您正在使用Rails 3并且您正在使用资源,则需要添加以下内容:

resources :questions do 
  member do
     put 'answer'
  end
end

这将创建类似/questions/#{id}/answer的路线。

答案不是HTTP动词,因此在您的路线中使用resources不会创建指向answer行动的路线。

根据评论进行编辑:

首先,如果您要更新或创建数据,则应使用putpost。使用get修改服务器上的数据是个坏主意。其次,我假设你会在每个问题上做一个答案。如果是这种情况,您应该对成员而不是集合执行操作。此外,在您的回答操作中,您有params[:id]。如果您尝试对集合而不是成员执行操作,则不会获得params[:id]