Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a rails multi select dropdown work

I am trying to make a multi select dropdown work with a dialog for search parameters. I can make the dropdown multi select but can't seem to get/pass the resulting data. (edited/new info will be in italics)

I believe that the root of the problem is that I need to change the permit section in my controller to reflect that I am passing a hash/array. If I look at the resulting record, the 2 fields that I am setting as multi-selects show as nil. However, if I force an errror, the parameters shown by rails show the correct choices. therefore, I believe that the problem might be with the permit section.

That looks like

 *def search_params
      params.require(:search).permit(:document_title,
                                     :summary,
                                     :owner,
                                     :category,
                                     :file_name,
                                     :doc_to_email,
                                     :categories_attributes => [:name])
    end*

I added the :categories_attributes => [:name] to try to get the controller to allow hashes but that didn't work.

The select field is

 <%= f.select :category[], options_for_select(@categories.sort), {:include_blank => true}, {:multiple => true, :size =>10}  %>

but that gives me

.erb where line #41 raised:

wrong number of arguments (0 for 1..2) Trace of template inclusion: app/views/searches/new.html.erb

I thought I had to set category as an array with the [] but obviously I'm missing something.

Category is a string field in the Searches table.

like image 677
Chris Mendla Avatar asked Sep 25 '22 20:09

Chris Mendla


1 Answers

You do not need the [] brackets after the field name as Rails adds those in automatically.

See the example here: http://apidock.com/rails/ActionView/Helpers/FormTagHelper/select_tag

select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>".html_safe, multiple: true
# => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option>
#    <option>Green</option><option>Blue</option></select>

In your case the selected values will be available as an array in params[:search][:category] after the form is submitted.

If you use strong parameters, also make sure you have :category => [] in the permit list.

like image 187
Mate Solymosi Avatar answered Oct 27 '22 04:10

Mate Solymosi