2012-01-08 39 views
0

我现在有看起来像这样的秩序和形象的模型:结合ActiveRecord的结果在Ruby中

class Order < ActiveRecord::Base 
    has_many :images 
end 

class Image < ActiveRecord::Base 
    belongs_to :order 
end 

现在,我想做到以下几点:

<% @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 2012-01-08 18:50:10