0

I have an Activity menu, that should display items from two different models sorted by created_at.

I know how to iterate and sort items from individual models, however when I try to combine the results. I'm then unable to iterate through as the attributes would be different. So below doesn't make sense.

<% @post_and_events = @posts + current_user.events %>
  <% for both in @post_and_events %>
    <%= both.? %>
  <% end %>
<% end %>

As posts have different attributes from events.

In my head I'm thinking to sort them separately, however I'm unsure how to display @post and @events sorted as a group, instead of show results of one then the other.

Follow up to: this

Community
  • 1
  • 1
RedRory
  • 632
  • 1
  • 6
  • 18

3 Answers3

1

You can try this:

<% @post_and_events = (@posts + @events).sort_by{|pe| pe.created_at} %>

and if you want to show different html parts for each do:

<% @post_and_events.each do |pe| %>
  <% if pe.is_a? Post %>
    ...
  <% else %>
    ...
  <% end %>
Lazarus Lazaridis
  • 5,803
  • 2
  • 21
  • 35
1

You should create the dataset that you'll be working with in your controller, rather than in the view. You can do that with something like this:

first_thing  = FirstModel.all
second_thing = SecondModel.all
@both_things = (first_thing + second_thing).sort_by { |thing| thing.created_at }

You could iterate through your dataset in the view, selectively displaying attributes using something like this:

<% @both_things.each do |thing| %>
  <%= thing.attribute_one if thing.is_a? FirstModel %>
  <%= thing.attribute_two if thing.is_a? SecondModel %>
<% end %>

That could get out of hand, if you've got a lot of different possibilities/attributes. In that case, I might suggest setting up two partials _show_thing_one.html.erb and _show_thing_two.html.erb for example. In your view, selectively use the partial based on the thing being displayed:

<% @both_things.each do |thing| %>
  <% if thing.is_a?(FirstModel) %>
    <%= render 'show_thing_one', thing: thing %>
  <% elsif thing.is_a?(SecondModel) %>
    <%= render 'show_thing_two', thing: thing %>
  <% end %>
<% end %>

In each partial, you could use the variable thing to refer to the item being passed in (that's what the thing: thing part of the render line is doing, which you can read more about here). So each partial could be fully customized for FirstModel or SecondModel.

James Chevalier
  • 10,604
  • 5
  • 48
  • 74
0

Would something like below work for you? I am not sure if this is what you are looking for

<% @values = @posts.collect(&post_attribute) + current_user.user_attribute %>
<% for value in @values %>
  <%= value%>
<% end %>
usha
  • 28,973
  • 5
  • 72
  • 93