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

Dan*_*zon 0 ruby ruby-on-rails

我试图从我的数据库中检索所有帖子,并按照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
Run Code Online (Sandbox Code Playgroud)

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

编辑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
Run Code Online (Sandbox Code Playgroud)

Ani*_*nil 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
Run Code Online (Sandbox Code Playgroud)

要检索非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
Run Code Online (Sandbox Code Playgroud)

更改is not null> 0整数CATEGORY_ID或者!= ''如果你的表中包含"",而不是空值.

祝好运.