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

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

编辑:

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 

每次迭代都会覆盖@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的所有post,请尝试以下操作:

 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 

如果您的表包含”而is not null ,则对于整数category_id,更改is not null ,或者!= ''

祝好运。