2012-01-08 4 views
0

にActiveRecordの結果を組み合わせ私は現在、次のようになり注文とイメージモデルを持っているRubyの

<% @order.images.each do |image| %> 
    <%= image.format %> x 
    <%= image.amount %> 
    <%= number_to_currency(image.price) %><br/> 
<% 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のオブジェクトの配列です。

1

あなたはassociation extensionsを使用することができます。

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 

そして、ビューで:

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

はそのアプローチを知りませんでした。偉大な作業をする必要がありますが、価格フィールドはデータベースフィールドではないため、これはうまくいかないので、質問を少し簡略化しました。しかし、将来も十分に面白いです。 – Sweam

関連する問題