Triggering Rails Flash Message on Empty Selection List

This post describes how to trigger a Rails Flash Message on the page based on certain criteria. Our criteria is that the user has to select as least one of the stores in the checkbox list. If he clicks “Continue” with all store checkboxes cleared we’re going to say, “Hey, Select Something Already!” Here’s the Store Checkbox List. (Those of you who follow this blog might have seen it before. :)

The Setup

To setup our logic we’re going to go into debug mode.  The Store Checkbox List is passing a parameter array called store_ids, so we’re going to use pretty simple logic of determining if store_ids contains any values. If store_ids is nil, we’ll display a flash error message and redisplay the page.

The Controller

Here is how we’ll handle the nil test in the controller. I love how Rails makes it possible to do in a couple lines of code what used to be really, really hard.

The Pudding

Here’s the proof that our approach worked. 

The Tests

Let’s not forget our tests! Again, just a few lines of code in our RSpec Request page contents tests. We’ve generated our checkbox list earlier in the page describe tests, so here we’ll set each checkbox on the page to false, click the “Continue” button, and expect to see our Flash error message HTML wrapping.