在Rails控制器中的循环内循环

时间:2012-06-05 19:48:38

标签: ruby-on-rails ruby

我正在尝试从我的数据库中检索所有帖子,并按照DESC顺序列出它们的创建日期。到目前为止,我已经设法测试属于一个类别的所有帖子,但我想显示所有帖子,无论他们属于哪个类别。我知道我必须循环到每个类别,并从每个类别获取帖子,但我不知道如何。这是我的代码:

编辑:

  def index
    @institution = Institution.find(current_user.institution.id)
    @categories = Category.all
    @categories.each do |category|
      @posts = Post.where("category_id = ? and institution_id = ?", category, @institution).order("created_at DESC")
    end
    authorize! :read, @post
    respond_with(@posts)
  end

有人可以指出我正确的方向吗?

编辑2:我的观点(index.html.haml)

%h1 Listing posts

%table
  %tr
    %th Title
    %th Description
    %th User
    %th Category
    %th Type
    %th Class
    %th Institution

  - @posts.each do |post|
    %tr
      %td= post.title
      %td= post.description
      %td= post.user_id
      %td= post.category_id
      %td= post.institution_id

1 个答案:

答案 0 :(得分:6)

每次迭代都会覆盖@posts。 试试这个:

def index
    @institution = Institution.find(current_user.institution.id)
    @categories = Category.all
    @posts = []
    @categories.each do |category|
      tposts = Post.where("category_id = ? and institution_id = ?", category, @institution).order("created_at DESC")
      @posts += tposts if tposts
    end
    authorize! :read, @post
    respond_with(@posts)
end

要检索非null category_id的所有帖子,请尝试以下操作:

def index
    @institution = Institution.find(current_user.institution.id)
    @categories = Category.all
    @posts = Post.where("category_id is not null and institution_id = ?", @institution).order("created_at DESC")
    authorize! :read, @post
    respond_with(@posts)
end

如果您的表包含''而不是null,则将is not null更改为> 0以获取整数category_id或!= ''

祝你好运。