0

In my controller I do:

@categories = Category.all
for i in @[email protected]
   @allposts.push(Post.where(:Category => i))
end

In views(haml) i do

<% @allposts.each do |posts, slots| %>
  <% @slots.each do |post| %>
    <%= post.Title %>
  <% end %>
<% end %>

And i see this error:

undefined method `each' for nil:NilClass on @slots.each do |post|.

Thank you in advance.

2
  • Why are you keep trying to use @slots ? As inside the block you created as |posts, slots|... Commented May 5, 2014 at 16:45
  • @Saska If Category is associated with model Post with 1-M relationship then you can simply loop over @categories like @categories.each do |category| category.posts to get all the posts associated with a given category. Why to make multidimensional arrays and complicate it? Commented May 5, 2014 at 17:37

2 Answers 2

3

You haven't defined @slots in the method.Perhaps you mean slots.

<% @allposts.each do |posts, slots| %>
  <% slots.each do |post| %>
    <%= post.Title %>
  <% end %>
<% end %>
Sign up to request clarification or add additional context in comments.

Comments

1

Fix is :

<% @allposts.each do |posts, slots| %>
  <% slots.each do |post| %>  # <--- see I removed @ symbol
    <%= post.Title %>
  <% end %>
<% end %>

Your block variable is slots, and you attempted as @slots. Which I think is a typo. As there is no such @slots variable defined, you got nil, when you wanted to use it. There is a sweet difference between local variable and instance variable. If you don't defined anywhere a local variable say foo, you will be ended up with undefined local variable or method if you want to use foo anywhere else.But for instance variable, no error, you will silently get nil.

2 Comments

Just 41 sec behind from your answer :)
@Pavan Yes.. may be 10 more seconds less.. My mouse's right click was not working.. :)

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.