开发者

Rails listing problem

开发者 https://www.devze.com 2023-03-06 01:00 出处:网络
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).

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/a开发者_开发知识库pp/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?


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 a before_filter in your application_controller.rb.

class ApplicationController < ActionController::Base
    ...
    before_filter setup_items
    ...
    def setup_items
        @items = Item.all
    end
    ...
end

This assumes that all controllers using this layout extend the application controller.


Make sure your controller has this:

@items = Item.all

Then in your view you want this :

<div id="leftcolumn">
   <% @items.each do |link| %>
     <%= link_to link.title, link if link.title%>
   <% end %>
</div>

It could be failing because one of the links does not have a title.

0

精彩评论

暂无评论...
验证码 换一张
取 消