Rails 5 adds a hidden field on collection radio buttons

Prajakta Tambe

By Prajakta Tambe

on May 18, 2016

This blog is part of our  Rails 5 series.

Consider the following form which has only one input role_id which is accepted through collection_radio_button.

1<%= form_for(@user) do |f| %>
2  <%= f.collection_radio_buttons :role_id, @roles, :id, :name %>
3  <div class="actions">
4    <%= f.submit %>
5  </div>
6<% end %>

In the controller, we can access role_id using the strong parameters.

1def user_params
2  params.require(:user).permit(:role_id)
3end

When we try to submit this form without selecting any radio button in Rails 4.x, we will get 400 Bad Request error with following message.

1ActionController::ParameterMissing (param is missing or the value is empty: user):.

This is because following parameters were sent to server in Rails 4.x .

1Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "commit"=>"Create User"}

According to HTML specification, when multiple parameters are passed to collection_radio_buttons and no option is selected, web browsers do not send any value to the server.

Solution in Rails 5

Rails 5 adds hidden field on the collection_radio_buttons to avoid raising an error when the only input on the form is collection_radio_buttons. The hidden field has the same name as collection radio button and has blank value.

Following parameters will be sent to server in Rails 5 when above user form is submitted:

1Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "user"=>{"role_id"=>""}, "commit"=>"Create User"}

In case we don't want the helper to generate this hidden field, we can specify include_hidden: false.

1<%= f.collection_radio_buttons :role_id, Role.all, :id, :name, include_hidden: false %>

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.