1

我知道出了什么问题,但在修复它时遇到了麻烦。

为了再次解释我的情况,我有 3 个要素:工作、问题和答案。所有的关系都在下面设置。扩展我之前与 Jobs > Questions 关系有关的问题,我现在在 Jobs > Questions > Answers 中添加了 Answers 关系。

所以,在我的 routes.rb 中有一个新资源,我遇到了路由错误,我正在修复它。当我进入表单 Answers#new 页面并不得不修改 form_for 脚手架并在 Answers 控制器中的Create操作上构建时,问题就出现了(您可以在下面查看我的代码)。

我能够修复这些足以在新答案页面上显示表单,但是当我单击提交时,我收到此错误:

No route matches {:action=>"show", :controller=>"answers", :job_id=>nil, :question_id=>1, :id=>#<Answer id: 3, job_id: nil, question_id: 1, answer1: "", answer2: "", answer3: "", answer4: "", answer5: "", created_at: "2011-07-01 03:12:06", updated_at: "2011-07-01 03:12:06">}

从这个错误中,我可以看到我没有保存 job_id,我很确定这与我没有在我的答案创建操作或答案新 form_for 代码中正确调用 job_id 有关。我尝试了很多解决方案,但似乎没有任何效果。我觉得我已经接近我的创建操作,但无法做到正确。无论如何,提前感谢您的帮助,如果我没有为您提供足够的周边代码,请告诉我,我会添加它。

这个问题是这篇文章的延伸:Link_to Routing Issue With Nested Resources

PS我还添加了我的答案显示操作,因为如果我直接转到答案/ 1 / 它可以正常工作。我只是有一种感觉,如果我的创作动作是错误的,那么我的表演动作也是如此。

楷模:

class Job < ActiveRecord::Base
has_many :questions
has_many :answers

class Question < ActiveRecord::Base
belongs_to :job
has_many :answers

class Answer < ActiveRecord::Base
belongs_to :job
belongs_to :question

答案#新表格

<%= form_for(@answer, :url => job_question_answers_path(@answer.job_id, @question)) do |f| %>

答案创造行动

def create
@job = Job.find(params[:job_id])
@question = @job.questions.find(params[:question_id])
@answer = @question.answers.build(params[:answer])
if @answer.save
 redirect_to(job_question_answer_path(@answer.job_id, @answer.question_id, @answer)
end
end

答案显示动作

def show
 @job = Job.find(params[:job_id])
 @question = @job.questions.find(params[:question_id])
 @answer = @question.answers.find(params[:id])
end

有关我最新的 rake 路线,请参阅此https://gist.github.com/1057810 。我知道我不应该嵌套超过 1 层,但这对我来说是最简单和最快的解决方案。

再次感谢!

4

1 回答 1

0

基于此行:

No route matches {
  :action=>"show", :controller=>"answers", 
  :job_id=>nil, #Problem
  :question_id=>1, 
  :id=>#<Answer id: 3, job_id: nil, question_id: 1, answer1: "", answer2: "", answer3: "", answer4: "", answer5: "", created_at: "2011-07-01 03:12:06", updated_at: "2011-07-01 03:12:06">}

您可以看到job_id您的 Answer 对象中的 为 nil。您的表单助手使用job_question_answers_path需要 ajob_id和 a question_id,但由于job_id是 nil ( @answer.job_id),路由错误被破坏:

<%= form_for(@answer, :url => job_question_answers_path(@answer.job_id, @question)) do |f| %>

尝试明确设置@answer.job您的操作。AnswersController#new

def new
  # You may already have code that does this...
  @answer = Answer.new

  # Guessing on param names here:
  @answer.question = Question.find params[:question_id]
  @answer.job = Job.find params[:job_id]

  # Alternatively, you can probably just set the ids, 
  # but the above will verify those objects exist first.
  @answer.job_id = params[:job_id]
  @answer.question_id = params[:question_id]
end
于 2011-07-01T16:00:19.780 回答