Published: February 5, 2025
6
5
84

If you've worked on a Rails app for long enough, you've had to get bulk actions work in a controller and likely ended up with a huge `case` statement that intercepts a `submit` value. Did you know how can hack Rails controllers to dispatch those to actions for you? šŸ§µšŸ‘‡

Image in tweet by Brad Gessler

The trick is to override a controller's `method_for_action` method and have it return the name of the batch method that's posted by the form's parameters.

Image in tweet by Brad Gessler

Here's what the form looks like that generates the payload for the `BatchActions` concern. The `form.submit` buttons are where all the magic happens. Note how the `value` attribute maps to the controller action.

Image in tweet by Brad Gessler

When you combine the two, you get a really clean way to handle bulk resource actions in Rails. It also makes it easier to integrate libraries like Pundit since the `before_action` works as you'd expect. I wrote more about how this works at https://terminalwire.com/artic... āœŒļø

Share this thread

Read on Twitter

View original thread

Navigate thread

1/4