fbpx

24 Mar /Rails Forms: Validating and Persisting Duplicate Parameter Names

Posted by Steve Gilliam

Building Rails forms is a pretty straightforward process but, once in a while, I run into a ‘gotcha’ that needs a simple solution. This week I was building a form where, if the user selects a particular subset of radio buttons, a text field is shown and the user is required to enter a string.  The form data is persisted using an enum to capture the radio button selection and a string attribute to capture the text entry if any.   The ‘gotcha’ is that the text field input needs to be placed in multiple places within the form,  and rails will ignore duplicate parameter names.

To allow the submission of the same input field multiple times, I added an empty array to the input name:

 

   <input id = “user_text_entry”, name=“user[text_entry][ ]”, placeholder=“Enter text” >
         => [,,”user’s text entered”]

 

More on parameter naming conventions can be found here.

 

To implement front end validations, I used jQuery’s :visible selector to ignore the hidden text fields.

 

var userTextEntry = $(‘.text-required-radio-box’).find(‘*’).filter(‘:input#user_text_entry:visible');