0

我正在尝试从我的数据库中检索所有帖子,并根据它们的创建日期按 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
4

1 回答 1

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

要检索具有非空 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

更改is not null> 0整数 category_id 或者!= ''如果您的表包含 '' 而不是空值。

祝你好运。

于 2012-06-05T20:00:08.153 回答