I have the following controller that retrieves “subcategories”, and then loops through each subcategory, grabbing and storing what I’ve termed “circles” into an instance variable
def show
@sub_categories = Category.where(:parent => params[:id])
@sub_categories.each do |sub_cat|
i = 1
@circles[i] = Circle.where(:category_id => sub_cat.id)
i++
end
end
This is outputting an error. I’m coming from PHP and don’t know how to do this properly.
categories_controller.rb:9: syntax error, unexpected kEND
IMO you should just use a join:
To address the code you’ve written: adding to an array in Ruby is done with
<<. So you could rewrite your code as follows:But you’d better use
joinsto do it in one query, like I show above.Update based on pastebin:
There is no need to set
@circles.This is what your view should look like:
To prevent the N+1 queries problem, you have to do this in your controller: