2012-01-08 2 views
0

에서 액티브 결과를 결합 :나는 현재 다음과 같이 질서 및 이미지 모델이 루비

<% @order.images.each do |image| %> 
    <%= image.format %> x 
    <%= image.amount %> 
    <%= number_to_currency(image.price) %><br/> 
<% end %> 

이이 출력합니다 :

class Order < ActiveRecord::Base 
    has_many :images 
end 

class Image < ActiveRecord::Base 
    belongs_to :order 
end 

지금 내가 다음을 수행하고 싶습니다를 :

1x 30x30 € 1,00 
1x 12x12 € 2,10 
3x 30x30 € 3,00 
4x 12x12 € 8,40 

나는 이것을 이미지 형식으로 결합하여 금액과 가격을 합산하고 싶습니다. 하지만 여러 가지 방법을 시도해 봤지만 @ order.images는 단순한 배열이 아니라 Image 객체이기 때문에 아무 것도 작동하지 않는 것 같습니다. 이것은 내가 달성하고자하는 것입니다 :

5x 12x12 € 10,50  
4x 30x30 € 4,00 

답변

1

당신은 group_by를 사용하여 시도 할 수 :

@order.images.group_by(&:format).each do |format, images| 
    <%= "#{images.length}x #{format} #{number_to_currency(images.sum(&:price))" %> 
end 

트릭을 할해야합니다. images은 같은 값이 format 인 객체의 배열입니다. 보기에, 다음

class Order < ActiveRecord::Base 
    has_many :images do 
    def by_format 
     select('sum(amount) as amount_sum, sum(price) as price_sum').group('format') 
    end 
    end 
end 

과 :

1

당신은 association extensions을 사용할 수 있습니다

@order.images.by_format.each { |i| i.format,... i.amount_sum, ..., i.price_sum,... } 
+0

그 방법을 몰랐다. 대단한 일을해야하지만 가격 필드가 데이터베이스 필드가 아니기 때문에 약간의 단순화가되어 작동하지 않습니다. 미래를 위해 충분히 흥미 롭다. – Sweam

관련 문제