Loop within Loop in Rails Controller

前端 未结 1 1018
后悔当初
后悔当初 2021-01-17 03:40

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 t

1条回答
  •  再見小時候
    2021-01-17 04:10

    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
    

    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
    

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

    Good luck.

    0 讨论(0)
提交回复
热议问题