0

我有以下控制器,它检索“子类别”,然后循环遍历每个子类别,将我称之为“圆圈”的内容抓取并存储到实例变量中

  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

这是输出错误。我来自 PHP,不知道如何正确执行此操作。

categories_controller.rb:9: syntax error, unexpected kEND
4

2 回答 2

1

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])
于 2012-10-09T05:05:28.060 回答
0

each is a iterator

since u r collecting the circles for the selected subcategories, u can simply write it as

@subcategories.collect{|sc| Circle.where(:category_id => sc.id) }

it will return u the array of circles.

于 2012-10-09T05:05:35.507 回答