Rails 控制器中的循环内循环 [英] Loop within Loop in Rails Controller

查看:61
本文介绍了Rails 控制器中的循环内循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从我的数据库中检索所有帖子,并按照创建日期按 DESC 顺序列出它们.到目前为止,我已经设法测试了属于一个类别的所有帖子,但我想显示所有帖子,无论它们属于哪个类别.我知道我必须遍历每个类别,并从每个类别中获取帖子,但我不知道该怎么做.这是我的代码:

I am trying to retrieve from my database all posts and list them in DESC order with respect to their creation date. So far I have managed to test for all posts that belong to one category but I want to display all posts no matter what category they belong to. I know I have to loop trough each category, and get the posts from each but I dont know how to. Here is my code:

  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

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

Can someone please point me in the right direction?

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

EDIT 2: My view (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.试试这个:

You are overwriting @posts with each iteration. Try this:

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

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

To retrieve all posts with non null category_id, try this:

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改为>0 表示整数 category_id 或 != '' 如果您的表包含 '' 而不是空值.

Change is not null to > 0 for integer category_id or != '' if your table contains '' instead of nulls.

祝你好运.

这篇关于Rails 控制器中的循环内循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆