An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
How to submit an array using a Rails form
This article was originally posted on my blog.
Sometimes an array of data needs to be submitted in an HTML form. A form to send invites to a bunch of users for example. That'd just be a series of email fields; and in the controller; we'd want an array of the emails to iterate over and send invites.
Rails form helpers are set up to have a key and value for each field, so it's not immediately obvious how to send an array of data. But in Rails, there's always a way!
If we append []
to the name
of a field, it'll be parsed as an array! So for an array of emails to send invites; settingname
as invites[]
on all the email fields and gives us an array in the controller.
To generate the form, we can use the following code:
<%= form_with(scope: :invites, url: invite_path) do |form| %> <% 3.times do %> <!-- id has to be nil to prevent clashes as all fields would have the same id --> <%= form.email_field nil, id: nil, placeholder: "Email Address" %> <% end %> <%= form.submit %><% end %>
Passing nil
as the first argument to email_field
instead of a name gives us the []
we need for an array. The generated markup looks like:
<form action="/invite" accept-charset="UTF-8" data-remote="true" method="post"> <input type="hidden" name="authenticity_token" value="...."> <input placeholder="Email Address" type="email" name="invites[]"> <input placeholder="Email Address" type="email" name="invites[]"> <input placeholder="Email Address" type="email" name="invites[]"> <input type="submit" name="commit" value="Save Invites" data-disable-with="Save Invites"></form>
On the controller, we can use the submitted data as:
def create invited_users = params.require(:invites) p invited_users # => ["[email protected]", "[email protected]", "[email protected]"]end
To permit an array parameter in a nested form field, we can use the following pattern:
params.require(:product).permit(tags: [])
It's a little unintuitive but submitting arrays from a form can be a useful tool in your toolbox!
Original Link: https://dev.to/ayushn21/how-to-submit-an-array-using-a-rails-form-5cgl
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To