IMO you should just use a join:
@circles = Circle.joins(:categories).where(:categories => { :parent_id => params[:id] })
To address the code you've written: adding to an array in Ruby is done with <<
. So you could rewrite your code as follows:
@circles = []
@sub_categories.each do |sub_cat|
sub_cat.circles.each do |circle| # assumes Category has_many :circles
@circles << circle
end
end
But you'd better use joins
to 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:
<% @sub_categories.each do |sub_cat| %>
<div class="circle">
<header>
<h3 data-toggle="collapse" href="#<%= dom_id(sub_cat) %>-collapse"><%=sub_cat.name %></h3>
<ul id="<%= dom_id(sub_cat) %>-collapse" class="accordion-body collapse">
<li class="list-shadow"></li>
<% sub_cat.circles.each do |circle| %>
<li><%= link_to circle.title, circle, :remote => true, :method => 'get' %></li>
<% end %>
</ul>
</header>
</div><!--.circle-->
<% end %>
To prevent the N+1 queries problem, you have to do this in your controller:
@sub_categories = Category.includes(:circles).where(:parent => params[:id])