Today, I would like to talk about a topic which was kind of not existing in the world of activescaffold in the past: Batch Actions

which means trigger an action on more than one record.

In this post I will focus on update action. Actually, you will see it s quite easy to setup and it s quite powerful.

Batch Actions are not part of activescaffold core, if you would like to use them you have to install another plugin: ActiveScaffoldBatch

rails plugin install git://github.com/vhochstein/active_scafffold_batch.git 

Let me show you some of the possibilities you have using players controller of my little howto app. I recommend using jquery for my examples, cause datetime examples will work out of the box. (Prototype needs calendar_date_select plugin for this.)

Firstly, we have to enable players controller for batch updates:

class PlayersController < ApplicationController
  active_scaffold :player do |conf|
    ....
    conf.actions << :batch_base 
    conf.actions << :batch_update 
    ....
  end
end

If you hit reload in your browser you should see a new collection action ‘batch’, which will open a submenu ‘Update’ on hover.
Please click on that link and you will see a batch_update form.

Change team for all players:

  • Change value of corresponding select box to ‘Replace’
  • select new team
  • press Batch Update Button

Set name attribute to null:

  • Change value of corresponding select box to ‘Null’
  • press Batch Update Button

Revert prev action and set name attribute to a name you like:

  • Change value of corresponding select box to ‘Replace’
  • Enter new name
  • press Batch Update Button

Increase salary for all players by 5%.

  • Change value of corresponding select box to ‘+’
  • Enter 5
  • Select % instead of abs
  • press Batch Update Button

Change Birthday of all players. Should be one week earlier.

  • Change value of corresponding select box to ‘-‘
  • Enter 1
  • Select week
  • press Batch Update Button

All examples so far changed all records, but for sure you can define a search condition. Batch Update will only process records, which fullfill current search conditions.

For example: search for some players, which you want to set to injured state.

However, sometimes it s not so easy to define a search condition, which covers all records you would like to update. If you are facing such an issue you might want to combine with mark action.

First step is to enable mark action in players controller

class PlayersController < ApplicationController
  active_scaffold :player do |conf|
    ....
    conf.actions << :mark
    ....
  end
end

As well we have to add mark route in routes.rb:

resources :players do 
  as_routes 
  post :mark_all, : on => :collection 
end 

That s it, now you ve got the option in batch update form to just affect marked records.

Wish you all a happy new year.