ruby - Loop within Loop in Rails Controller -
i trying retrieve database posts , list them in desc order respect creation date. far have managed test posts belong 1 category want display posts no matter category belong to. know have loop trough each category, , posts each dont know how to. here code:
edit:
def index @institution = institution.find(current_user.institution.id) @categories = category.all @categories.each |category| @posts = post.where("category_id = ? , institution_id = ?", category, @institution).order("created_at desc") end authorize! :read, @post respond_with(@posts) end can please point me in right direction?
edit 2: 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 |post| %tr %td= post.title %td= post.description %td= post.user_id %td= post.category_id %td= post.institution_id
you overwriting @posts each iteration. try this:
def index @institution = institution.find(current_user.institution.id) @categories = category.all @posts = [] @categories.each |category| tposts = post.where("category_id = ? , institution_id = ?", category, @institution).order("created_at desc") @posts += tposts if tposts end authorize! :read, @post respond_with(@posts) end to retrieve posts non null category_id, try this:
def index @institution = institution.find(current_user.institution.id) @categories = category.all @posts = post.where("category_id not null , institution_id = ?", @institution).order("created_at desc") authorize! :read, @post respond_with(@posts) end change is not null > 0 integer category_id or != '' if table contains '' instead of nulls.
good luck.
Comments
Post a Comment