I followed the example here to create a select multiple element for my form: Ruby on Rails -- multiple selection in f.select
However, when the submit button is clicked the values from the select field are not captured. I had the same issue when using checkboxes. It works when I change it to a text field, though. Am I missing something obvious? How do I capture the values that the user selects from the select field? My code is below.
The form: new.html.erb
<%= form_for @service do |f| %>
<div class="row">
<h3>Operating hours</h3>
<p>Please select the days you are open. Hold CTRL (Windows) or Command (Mac) to select multiple.</p>
<div class="form-group">
<div class="col-md-6">
<%= f.select(:work_days, [['Monday', 'Monday'],
['Tuesday', 'Tuesday'],
['Wednesday', 'Wednesday'],
['Thursday', 'Thursday'],
['Friday', 'Friday'],
['Saturday', 'Saturday'],
['Sunday', 'Sunday']
],{},
{ :multiple => true, :size => 7 }
) %>
</div> <!-- .col-md-6 -->
</div> <!-- .form-group -->
</div> <!-- .row -->
<!-- the code in the div below works -->
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label for="work_days">work days</label>
<%= f.text_field :work_days, placeholder: "Type the days you are available", class: "form-control", required: true, id: "work_days" %>
</div>
</div>
</div> <!-- .row -->
<div class="text-center">
<%= f.submit "Save", class: "btn btn-success" %>
</div>
<% end %>
The relevant controller code: services_controller.rb
class ServicesController < ApplicationController
# require the user to be logged in to edit and create, but not to view
before_action :set_service, except: [:index, :new, :create]
before_action :authenticate_user!, except: [:show]
before_action :is_authorised, only: [:listing, :update]
def new
@service = current_user.services.build
end
def create
@service = current_user.services.build(service_params)
if @service.save
redirect_to listing_service_path(@service), notice: "Saved..."
else
flash[:alert] = "Something went wrong..."
render :new
end
end
private
def set_service
@service = Service.find(params[:id])
end
def service_params
params.require(:service).permit(:title, :description, :work_days, :open_time, :close_time)
end
end