#routes.rb
resources :courses do
resources :chapters
end
章节/index.html.erb
<h1>Chapters</h1>
<table class="table table table-striped table table-hover">
<tr>
<th>Title</th>
<th>Chapter no</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @chapters.each do |chapter| %>
<tr>
<td><%= chapter.title %></td>
<td><%= chapter.chapter_no %></td>
<td><%= link_to 'Show', course_chapter_path(course_id: chapter.course.id, id: chapter.id) %></td>
<td><%= link_to 'Edit', edit_course_chapter_path(course_id: chapter.course.id, id: chapter.id) %></td>
<td><%= link_to 'Destroy', course_chapter_path(course_id: chapter.course.id, id: chapter.id), method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Chapter', new_course_chapter_path(course_id: @chapter.course.id, id: @chapter.id), class: 'btn btn-secondary' %>
我在章节的最后一行/index.html.erb中得到一个错误我一直在练习嵌套路由,并试图了解
<%= link_to 'New Chapter', new_course_chapter_path(course_id: params[:course_id]), class: 'btn btn-secondary' %>
对于新对象(章节(,您不需要传递章节id,因为您正在创建新对象(章(。
注意:这里我假设,你是从params得到课程id。
参考新的行动路线
new_course_chapter GET /courses/:course_id/chapters/new(.:format) chapters#new
对于新的操作,您应该提供course_id,而不提供章节的id
<%= link_to 'New Chapter', new_course_chapter_path(course_id: params[:course_id]), class: 'btn btn-secondary' %>