2013-04-13 4 views
0

저는 Ruby on Rails에 익숙하지 않아 쿼리를 배열에 결합하는 방법을 파악하고 시간에 따라 출력 할 수 있도록 정렬합니다. 내 컨트롤러에서RoR : 배열로 다중 루프 결합 및 배열

나는이 있습니다

<%= media.created_time %> 
:

<% @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%> 

나는 또한이에 의해 생성 된 시간을 알아낼 수 : 내보기에

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

을 나는이 있습니다

각 루프에 있습니다.

이제 루프를 배열에 넣은 다음 created_item을 기반으로 정렬하는 방법을 배우고 있습니까? 간단한 구문이 있습니까?

감사합니다. 정렬

답변

2
<% (@[email protected]_media_items).each do |media| %> 
    <img src="<%= media.images.thumbnail.url%>"> 
<% end%> 

:

<%(@[email protected]_media_items). 
     sort{|a,b| a.created_at <=> b.created_at}. 
     each do |media| %> 
+0

워이 굉장합니다! 나는 창조 된 시간이 가장 빠른 것으로 분류되어 있다고 생각합니다. 현재부터 가장 빠른 방법은 무엇입니까? 또한, 두 개의 배열을 사용하는 것은 매우 간단합니다. 배열을 두 개 이상 삽입하고 정렬하려면 어떻게됩니까? <=>은 무엇을합니까? – hellomello

+1

sort {| a, b | - (a.created_at <=> b.create_at)}. 정렬 및 <=> 연산자가 작동하는 방법에 대한 좋은 설명을 보려면이 링크를 확인하십시오. http://stackoverflow.com/questions/2637419/understanding-ruby-array-sort – manoj

1

그것이 내가 대신 2 개 쿼리로, 1 개 쿼리를 작성하는 것이 좋습니다 것 같은 모델 인 경우.

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

여전히 2 개 쿼리가 필요하고이 같이 할 수있는 정렬 않는 경우,

컨트롤러 :

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

보기 :

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

오 와우, 그렇게하는 또 다른 간단한 방법! – hellomello