1

I have the following problem:

In Rails I have two Objects: Categories and Items One category has many items and one item belongs to one category.

Okay. There are no problems. But now, I want to display all existing categories in a sidebar on every page in my project.

I tried to do display them like:

<div class="sidebar">
  <% @categories.each do |category| %>
    <p><%= link_to category.title, category %></p>
  <% end %>
</div>

My root controller is categories. On my starting page the code above will work without any problems.

But when I click on a category I get the following exception:

*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*

Extracted source (around line #2):
2:     <% @categories.each do |category| %>

How can I fix this problem?

Sorry for my bad English!

1 Answer 1

1

You forget to set the @categories variable in the controller. You can either load the @categories in every action you need to display the sidebar or delegate the request to the view without setting an instance variable.

# in the controller

def action
  @categories = ...
end

# or in the view

<div class="sidebar">
  <% Category.all.each do |category| %>
    <p><%= link_to category.title, category %></p>
  <% end %>
</div>

If the code spans over multiple views/controllers, I would suggest you to extract the statement in a before_filter and/or a partial.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Now I have added before_filter :load_sidebar_categories def load_sidebar_categories @sb_categories = Category.all end in my application controller and it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.