Rails 列表问题
我生成了一个脚手架并创建了一个临时应用程序。我想在侧边栏上列出应用程序中各处的脚手架项目(在 application.html.erb 内)。 我的左栏在 application.html.erb 中看起来像这样:
> <div id="leftcolumn">
> <% @items.each do |link| %>
> <%= link_to link.title, link %>
> <% end %>
> </div>
单击每个项目将导致它的 Show 方法。 运行后,每当我尝试访问任何项目的任何方法时,它都会显示以下错误:
> NoMethodError in Items#show
>
> Showing F:/Rails/items-list/app/views/layouts/application.html.erb
> where line #17 raised:
>
> You have a nil object when you didn't expect it!
> You might have expected an instance of Array.
> The error occurred while evaluating nil.each
并且后面的代码是左列的代码。 我该如何解决这个问题?
I generated a scaffold and I created a casual application. I want to list the scaffold items on a sidebar, everywhere on the application (inside application.html.erb).
My left column, in application.html.erb looks like that:
> <div id="leftcolumn">
> <% @items.each do |link| %>
> <%= link_to link.title, link %>
> <% end %>
> </div>
Clicking on each item would lead to it's Show method.
After running that, whenever I try to access any method of any item, it shows me the following error:
> NoMethodError in Items#show
>
> Showing F:/Rails/items-list/app/views/layouts/application.html.erb
> where line #17 raised:
>
> You have a nil object when you didn't expect it!
> You might have expected an instance of Array.
> The error occurred while evaluating nil.each
And the followed code is the left column's code.
How can I fix that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Rails 正在抱怨,因为你试图将 nil 视为数组。如果没有发布 application.html.erb 的行号,我必须猜测,但我猜测
@items
为零。如果您将其包含在布局中,则需要确保在每个请求上都设置了
@items
数组。是吗?一种简单的方法是在 application_controller.rb 中放置一个before_filter
。这假设所有使用此布局的控制器都扩展了应用程序控制器。
Rails is complaining because you're trying to treat nil as an array. Without posting the line numbers for application.html.erb, I have to guess, but I'd guess that
@items
is nil.If you're including this in your layout, then you need to make sure that your
@items
array is set on every request. Is it? One easy way of doing this would be to put abefore_filter
in your application_controller.rb.This assumes that all controllers using this layout extend the application controller.
确保您的控制器具有以下内容:
然后在您的视图中您需要以下内容:
它可能会失败,因为其中一个
链接
没有标题。Make sure your controller has this:
Then in your view you want this :
It could be failing because one of the
links
does not have a title.