【问题标题】:Link_to Routing Issue With Nested Resources嵌套资源的 Link_to 路由问题
【发布时间】:2011-06-21 06:12:22
【问题描述】:

我有两个模型 Jobs 和 Questions。一份工作有很多问题,而问题属于一份工作。 我已经在模型中设置了资源以及路线。我在尝试链接到 questions#index 页面上问题控制器的 Show 方法时遇到问题。我的 rake 路线说路径应该是 job_question_path,其中两个必要的 :id 是 :job_id 和 :id ,所以我尝试了:

<td><%= link_to 'Show', job_question_path(@job, question) %></td>

并得到错误:

No route matches {:action=>"show", :controller=>"questions", :job_id=>nil, :id=>#<Question id: 1, job_id: 1, question1: "sfsdfssfs", question2: "sfsdfs", question3: "sfsdf", question4: "sfsdfsf", question5: "sfsfsfs", created_at: "2011-06-21 03:25:12", updated_at: "2011-06-21 03:25:12">}

我已经尝试了多种其他组合,但似乎没有任何效果,我不断收到:

No route matches {:action=>"show", :controller=>"questions", :job_id=>nil } 

或两者兼而有之。

我没有得到的部分是我可以输入 url /jobs/1/questions/1 并将我带到显示页面,所以我假设我的 questions#show 方法没问题。有关我的其余代码,请参见下文。

问题#索引视图

<% @questions.each do |question| %>
 <tr>
  <td><%= question.question1 %></td>
  <td><%= question.question2 %></td>
  <td><%= question.question3 %></td>
  <td><%= question.question4 %></td>
  <td><%= question.question5 %></td>
  <td><%= link_to 'Show', job_question_path(@job, question) %></td>
</tr>

问题控制器

def index
 @questions = Question.all

 respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @questions }
 end
end

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

 respond_to do |format|
  format.html # show.html.erb
  format.xml  { render :xml => @question }
 end
end

型号

class Job < ActiveRecord::Base
 has_many :questions

class Question < ActiveRecord::Base
  belongs_to :job

Routes.rb

 root :to => "pages#home"

 resources :jobs do
  resources :questions
 end

 get "pages/home"
 get "pages/about"
 get "pages/contact"

请参阅https://gist.github.com/1032734 了解我的 rake 路线。

提前感谢您的任何帮助,我已经有一段时间了,只是无法找出解决方案。如果您需要更多信息,请告诉我。

【问题讨论】:

    标签: ruby-on-rails link-to nested-resources


    【解决方案1】:

    可能是这样吗?

    问题#索引视图

    <% @questions.each do |question| %>
     <tr>
      <td><%= question.question1 %></td>
      <td><%= question.question2 %></td>
      <td><%= question.question3 %></td>
      <td><%= question.question4 %></td>
      <td><%= question.question5 %></td>
      <%= link_to 'Show', job_question_path(question.job_id, question.id) %>
    </tr>
    

    它必须工作。或者您在 Questions 表中没有“job_id”字段吗?

    【讨论】:

    • 那没用,我收到undefined method 'job_id' for nil:NilClass
    • 就是这样,我搞砸了 index 操作,但在破坏它后,将其恢复为原始状态。
    • &lt;%= link_to 'Show', job_question_path(question.job_id, question.id) %&gt; - 就是这样,它成功了!谢谢!我想我也明白为什么!
    • 我从头说起))看书,因为你写的代码不是很好。祝你好运。 Rails 是最好的。
    猜你喜欢
    • 1970-01-01
    • 2011-07-09
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多