---
title: "Rails 5 adds a hidden field on collection radio buttons"
description:
  "Rails 5 adds a hidden field on collection radio buttons to handle situation
  when user submits a form without selecting any radio button."
canonical_url: "https://www.bigbinary.com/blog/rails-5-add-a-hidden-field-on-collection-radio-buttons"
markdown_url: "https://www.bigbinary.com/blog/rails-5-add-a-hidden-field-on-collection-radio-buttons.md"
---

# Rails 5 adds a hidden field on collection radio buttons

Rails 5 adds a hidden field on collection radio buttons to handle situation when
user submits a form without selecting any radio button.

- Author: Prajakta Tambe
- Published: May 18, 2016
- Categories: Rails 5, Rails

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

```ruby
<%= form_for(@user) do |f| %>
  <%= f.collection_radio_buttons :role_id, @roles, :id, :name %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
```

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

```ruby
def user_params
  params.require(:user).permit(:role_id)
end
```

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.

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

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

```ruby
Parameters: {"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](https://github.com/rails/rails/pull/18303)
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:

```ruby
Parameters: {"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`.

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

## Links

- [Human page](https://www.bigbinary.com/blog/rails-5-add-a-hidden-field-on-collection-radio-buttons)
