Rails 4: Working with Strong Parameters with Dynamic Forms

My development path has finally brought me to the avenue of Rails 4 and Ruby 2.1. The land of turbolinks, strong parameters and swift binary coding…

Now that I have tried to be a little poetic, let me get to the point of this blog post.

I am working on a project that calls for a user to dynamically add items to a form (by clicking on an add more link). Everything works as expected (on the front end), but strong parameters certainly did not like this idea. Here is how I solved the issue(s) I was having.

CoffeeScript

Form

Controller

Models

The focal point of this post is more in the view and controller. If you will notice in the code example above, we are setting the child index of the nested attributes with the current time.

If you were to use the traditional way of accepting these attributes with strong params, Rails would kick out the line_items hash. To allow for a dynamic form submission with a nested form, you have to use whitelist the entire line_items_attributes hash because we are dynamically setting the child_index.

From the Rails documentation: “Imagine a scenario where you want to whitelist an attribute containing a hash with any keys…” Rails Guide: Strong Params

Happy Hunting!