2012-09-10 6 views
0

그룹 데이터를 표시하는 가장 좋은 방법은 무엇입니까? 정렬 된 데이터 그룹화

가 현재 내 컨트롤러에서 내가 가진 :
@items = Item.order("group_name") 

그런 다음 내보기에 내가 그것을 통해 반복 할 수

- @items.each do |item| 
    %p= item.name 

같은 것을 생산하는 깨끗하고 가장 효율적인 방법이 될 것입니다 무엇 :

<strong>Group Name 1</strong> 
<p>Item 1</p> 
<p>Item 2</p> 
<strong>Group Name 2</strong> 
<p>Item 1</p> 

답변

1

컨트롤러

@items = Item.sanitized_and_ordered 

모델

class Item << ActiveRecord::Base 
scope :ordered_group ,order('group_name') 

class << self 
    def sanitized_and_ordered 
     ordered_group.group_by {|item| item.group_name} 
    end 
end 
end 

보기

- @items.each_pair do |key,value| 
    %p= key 
    - value.each do |item| 
     %p= item.name 
관련 문제