0

データベースからすべての投稿を取得し、作成日に関して DESC 順にリストしようとしています。これまでのところ、1 つのカテゴリに属する​​すべての投稿をテストすることができましたが、どのカテゴリに属していてもすべての投稿を表示したいと考えています。各カテゴリをループして、それぞれから投稿を取得する必要があることはわかっていますが、方法がわかりません。これが私のコードです:

編集:

  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

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

整数の category_idの場合、またはテーブルに null ではなく '' が含まれている場合は、に変更is not nullします。> 0!= ''

幸運を。

于 2012-06-05T20:00:08.153 に答える