0

当我尝试通过单击如下所述的编辑链接从其显示页面编辑子资源(课程)时,我遇到了嵌套路由问题。涉及两个类:单元和课程。我不明白为什么 Rails 试图路由到课程控制器(Units 的父级)。

任何帮助将不胜感激。

我收到此错误和网址

http://localhost:3000/units/3/lessons/13/edit
Routing Error

No route matches {:action=>"show", :controller=>"courses", :id=>nil}

config/routes.rb 资源:课程做资源:单元结束

resources :units do
    resources :lessons
end

** 来自 rake 路线**

    unit_lessons GET    /units/:unit_id/lessons(.:format)            lessons#index
                 POST   /units/:unit_id/lessons(.:format)            lessons#create
 new_unit_lesson GET    /units/:unit_id/lessons/new(.:format)        lessons#new
edit_unit_lesson GET    /units/:unit_id/lessons/:id/edit(.:format)   lessons#edit
     unit_lesson GET    /units/:unit_id/lessons/:id(.:format)        lessons#show

点击链接的代码

<%= link_to "Edit Lesson", edit_unit_lesson_path(@unit, @lesson ) %>

课程控制器

class LessonsController < ApplicationController
  before_filter :find_unit
  before_filter :find_lesson, :only => [:show,:edit,:update,:destroy]
  .
  .
  .
private
def find_unit
  @unit = Unit.find(params[:unit_id])
end

def find_lesson
  @lesson = @unit.lessons.find(params[:id])
end

服务器日志文件

Started GET "/units/3/lessons/12/edit" for 127.0.0.1 at 2012-08-02 14:50:55 +0200
Processing by LessonsController#edit as HTML
    Parameters: {"unit_id"=>"3", "id"=>"12"}
    Unit Load (0.1ms)  SELECT "units".* FROM "units" WHERE "units"."id" = ? LIMIT 1  [["id", "3"]]
Lesson Load (0.1ms)  SELECT "lessons".* FROM "lessons" WHERE "lessons"."unit_id" = 3 AND     "lessons"."id" = ? LIMIT 1  [["id", "12"]]
Rendered lessons/_form.html.erb (3.4ms)
Rendered lessons/edit.html.erb within layouts/application (4.4ms)
Completed 500 Internal Server Error in 7ms

ActionController::RoutingError (No route matches {:action=>"show", :controller=>"courses", :id=>nil}):
app/views/lessons/edit.html.erb:8:in   `_app_views_lessons_edit_html_erb___3830769233446763788_70188197130200'
4

1 回答 1

0

找到了。该链接是表体的一部分,使用 .each 迭代器构建。我需要将名称从“@lesson”更改为“lesson”,因为这是构建表时引用的名称。

对于遇到类似问题的其他人,我将功能代码放在下面。

<tbody>  
  <% @unit.lessons.each do |lesson| %>
    <tr>
      <td><%= link_to lesson.lesson_name, [@unit, lesson] %></td>
      .
      .
      .
      <td><%= link_to 'Edit', edit_unit_lesson_path(@unit, lesson ) %></td>
   </tr>
 <% end %>
 </tbody>
于 2012-08-02T21:07:47.990 回答