Selectively modifying attr_accessible

I came across the need to have a user list with checkboxes for ‘admin’ and ‘fleet_commander’ to allow them to be set. Which works great- until you realise that your user model is protected from forms setting those fields!

This was using the ‘Toggle Attributes with Ajax’ recipe from ‘Advanced Rails Recipes’- an excellent book, and one I’d recommend.

Essentially, I had a remote update function using AJAX, which sent a user params hash with the appropriate value set. However, to let the form update the model, I had to use some class_eval magic:

def update
  1.     if current_user.admin?
  2.       User.class_eval('attr_accessible (usual stuff), :admin, :fleet_commander')
  3.     end
  4.     # continue onwards with updating using update_attributes
  5.   end

This temporarily adds the :admin and :fleet_commander attributes to the list of accessible attributes by calling attr_accessible in the context of the User class. Hope this helps someone in the same scenario!