Software engineer, data guy, Open Source enthusiast, New Hampshire resident, husband, father. Fan of guitars, hiking, photography, homebrewing, sarcasm.
Creating a Ruby on Rails admin form to bulk update multiple models
For my rails photo gallery site I needed the ability to bulk add descriptions and tags to my images. Finding, loading, editing, saving each photo individually is painful. I decided to create a form to edit a page of images at one time.
Added a ‘get’ route for the form. edited file: config/routes.rb
Added the bulk_update method to the images controller. Edited file: app/controllers/images_controller.rb
Add the view for the bulk_update action. The form_tag posts to another controller action. The each loop shown below outputs the tabular image data, and the fields_for method uses a partial to render the form fields. file: app/views/images/bulk_update.erb
The field_for renders the partial: bulk_update_form_fields. This partial simply outputs the form elements. file: app/views/images/_bulk_update_form_fields.html/erb
The above form submits to “admin_images_bulk_update_save_path”. The post route for the form. edited file: config/routes.rb
Added the bulk_update_save method to the images controller. The update method on the Image object accepts the keys and values from the submitted form data to update each Image model. The rest of the code collects errors, and redirects the user back to the form action. edited file: app/controllers/images_controller.rb
Last I added a before_filter method to authenticate admin users for these controller actions. edited file: app/controllers/images_controller.rb
The end result is a form that allows me to bulk edit my photos with pagination.