Question

I'm trying to sort out how to loop through two object arrays and display them in mixed order in a view – by the date they were created.

Here's my current controller code, that only displays Posts based on the category you're in, or, based on a search query:

def browse
  @user = current_user
  if params[:category]
    @category = Category.find(params[:category])
    @posts = @category.posts.page(params[:page])
  else
    @posts = Post.search(params)
  end
end    

In the view, I just loop through and output these like so:

- if @posts
  - @posts.each do |post|
    = post.name
    = post.content

What I'd like to do, is instead of referencing posts via the instance variable @posts... I'd like to create a new variable (ie: @everything) – that pulls objects from the Post class and the Comment class, pops them into the same array, and allows me to loop through and output each respectively in my view, like this:

Ideal controller:

def browse
  @user = current_user
  if params[:category]
    @category = Category.find(params[:category])
    @everything = @category.everything(params[:page]) # ... combination of comments and posts
  else
    @everything = Everything.search(params)
  end
end    

Ideal view:

- if @everything
  - @everything.each do |e|
    - if e.type == 'post'
      = e.name
      = e.content
    - else 
      = e.comment

Any help/guidance is appreciated. I'm just not sure how to approach this.

Was it helpful?

Solution

You would do this type of thing (to get you started)

def browse
  @user = current_user
  @everything = @category.posts | @category.comments
end 

In the view

%ul= render @everything

Make sure there is a views/comments/_comment.html.haml and a views/posts/_post.html.haml files.

Or you could render a specific partial and handle any differences in there

%ul= render :partial => shared/everything_item, :collection => @everthing
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top