24 Oct 2009

Adding multiple column calculations to ActiveScaffold

Recently I have been making great use of the excellent ActiveScaffold for a Ruby on Rails project I have been hired to create.

ActiveScaffold (AS) makes it really easily to do a calculation on the columns, for example displaying the average of a column. In your controller you just need to do:

active_scaffold :sale do |config|
config.columns[:product_profit].calculate = :avg

However my client wanted both averages and totals at the bottom, so From reading the documentation and a quick web search it didn't look to be a pre-built way to do this, so I had to look at customising the ActiveScaffold.

I wanted to be able to set calculate the standard way with a single option, or have an array of options:

config.columns[:chassis_profit].calculate = :avg
config.columns[:chassis_profit].calculate = [:sum, :avg]

The answer was to be found in vendor/plugins/active_scaffold/frontends/default/views/_list_calculations.html.erb. This file was responsible for calling the caluation and displaying the result. The chosen calculation option was accessable via column.calculate. I needed a way to handle both single values and arrays. The following code allowed me to iterate over an array, but still works if column.calculate was a single value:

<% for calculation_type in [*column.calculate] -%>
column.calculate = calculation_type
<% end -%>

As I looped over the array I set column.calculate to each single value, so I did not affect the way AS worked.

No comments:

Post a Comment