0

I'm new to Ruby on Rails, and I'm trying to figure out how to combine queries into an array, arrange them in order so they can output based on time.

In my controller I have this:

@tag_media_items = client.tag_recent_media('cats')
@location_media_items = client.location_recent_media('412421')

In my views I have this:

<% @tag_media_items.each do |media| %>
<img src="<%= media.images.thumbnail.url%>">
<% end%>

<% @location_media_items.each do |media| %>
<img src="<%= media.images.thumbnail.url%>">
<% end%>

I can also figure out the time that it was created by this:

<%= media.created_time %>

on each of the loop.

Now I'm learning how to put the loop into an array and then arrange it based on created_item? Is there a simple syntax for this?

Thanks!

hellomello
  • 8,219
  • 39
  • 151
  • 297

2 Answers2

2
<% (@tag_media_items+@location_media_items).each do |media| %>
   <img src="<%= media.images.thumbnail.url%>">
<% end%>

For sorting:

<%(@tag_media_items+@location_media_items).
        sort{|a,b| a.created_at <=> b.created_at}.
        each do |media| %>
manoj
  • 1,655
  • 15
  • 19
  • woah this is awesome! I think the created time is sorted by earliest to present. How do I do from present to earliest? Also, this seems really simple with two arrays, what happens if I wanted to insert more than 2 arrays and do sort? what does <=> do? – hellomello Apr 13 '13 at 06:36
  • 1
    sort{|a,b| -(a.created_at <=> b.create_at)}. For good explanation on how sort and <=> operator works, check this link http://stackoverflow.com/questions/2637419/understanding-ruby-array-sort – manoj Apr 13 '13 at 06:45
1

If it is the same model I would suggest to write 1 query, instead of 2 queries.

@media_items = client.recent_media_of_tag_and_location('cats', '412421')

If you still need 2 queries and do sorting you can do like this,

Controller:

@media_items = @tag_media_items | @location_media_items 
@sorted_items = @media_items.sort_by &:created_at

View:

<% @sorted_items.each do |media| %>
  <img src="<%= media.images.thumbnail.url%>">
<% end%>
Srikanth Jeeva
  • 3,005
  • 4
  • 38
  • 58