嵌套资源3个级别

时间:2011-07-01 03:26:31

标签: ruby-on-rails controller routes nested-resources

我知道出了什么问题,但我无法修复它。

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

所以,在我的routes.rb中有一个新资源我遇到了路由错误,我正在修复这个错误。问题发生在我进入Answers#new页面并且必须修改form_for脚手架并在Answers控制器中构建创建操作时(您可以在下面看到我的代码)。

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

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

P.S。我还添加了我的答案显示动作,因为虽然它正常工作,如果我直接去答案/ 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

答案#new表格

<%= 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

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

再次感谢!

1 个答案:

答案 0 :(得分: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为零。您的表单助手使用的job_question_answers_path需要job_idquestion_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
相关问题