rails form select
To create a select form field in Ruby on Rails, you can follow these steps:
Start by opening the view file where you want to add the form select field. This could be an HTML file with a
.html.erb
extension.Inside the form block, use the
select
method to create the select field. Theselect
method takes two arguments: the name of the attribute you want to assign the select field to, and a collection of options for the select field. Here's an example:
<%= form.select :color, ['Red', 'Green', 'Blue'] %>
In this example, :color
is the name of the attribute, and ['Red', 'Green', 'Blue']
is the array of options.
- If you want to pre-select a default option, you can pass an additional
selected
option to theselect
method. For example:
<%= form.select :color, ['Red', 'Green', 'Blue'], selected: 'Green' %>
In this case, the 'Green'
option will be pre-selected when the form is rendered.
- If you want to include a prompt or placeholder option at the beginning of the select field, you can pass a
prompt
orinclude_blank
option to theselect
method. For example:
<%= form.select :color, ['Red', 'Green', 'Blue'], include_blank: 'Select a color' %>
In this case, the select field will start with a blank option with the text 'Select a color'
.
- If you need to customize the HTML attributes of the select field, you can pass a
html_options
hash as the last argument to theselect
method. For example:
<%= form.select :color, ['Red', 'Green', 'Blue'], {}, class: 'form-control' %>
In this example, the class: 'form-control'
option adds the CSS class 'form-control'
to the select field.
- Finally, make sure to close the form block after adding the select field.
That's it! By following these steps, you can create a select form field in Ruby on Rails using the select
method.