我正在尝试将Sections
嵌入我的训练代码中Page
,我收到此错误:
undefined method `sections' for nil:NilClass
在此之前,我已成功嵌套Page
Subjects
。
请参阅下图中的错误,尝试将章节嵌套到页面中。
这就是我所做的:
sections_controller.rb:
class SectionsController < ApplicationController
layout 'admin'
before_action :confirm_logged_in
before_action :find_page
def index
@sections = @page.sections.sorted
end
private
def find_page
if params[:page_id]
@page = Page.find(params[:page_id])
end
end
end
我的观点:
index.html.erb:
<% @page_title = 'Sections' %>
<%= link_to('<< Back to Pages', {:controller => 'pages', :action => 'index', :subject_id => @page.subject_id}, :class => 'back-link') %>
<div class="sections index">
<h2>Sections</h2>
<%= link_to('Add New Section', {:action => 'new', :page_id => @page.id, :page_id => @page.id}, :class => 'action new') %>
<table class="listing" summary="Section list">
<tr class="header">
<th> </th>
<th>Page</th>
<th>Section</th>
<th>Content Type</th>
<th>Visible</th>
<th>Actions</th>
</tr>
<% @sections.each do |section| %>
<tr>
<td><%= section.position %></td>
<td><%= section.page.name if section.page %></td>
<td><%= section.name %></td>
<td><%= section.content_type %></td>
<td class="center"><%= status_tag(section.visible) %></td>
<td class="actions">
<%= link_to('Show', {:action => 'show', :id => section.id, :page_id => @page.id}, :class => 'action show') %>
<%= link_to('Edit', {:action => 'edit', :id => section.id, :page_id => @page.id}, :class => 'action edit') %>
<%= link_to('Delete', {:action => 'delete', :id => section.id, :page_id => @page.id}, :class => 'action delete') %>
</td>
</tr>
<% end %>
</table>
</div>
答案 0 :(得分:0)
好的,让我们一步一步走;首先导航到Sections索引路由,这是索引操作的代码:
"Undefined index: company"
您还有def index
@sections = @page.sections.sorted
end
应该设置before_action :find_page
:
@page
但这种情况从未发生过,因为def find_page
if params[:page_id]
@page = Page.find(params[:page_id])
end
end
nil 或者没有具有您传递的ID的Page。因此,@ page为nil,您调用nil.sections并触发您发布的异常。
如何将params[:page_id]
作为网址参数传递?
你是否有可能在路线中真正想要这样的东西:
page_id
如果是这样,正确的部分索引路径将如下所示:
resources :pages do
resources :sections
end