user109705
user109705

Reputation: 79

options_for_select Rails 4

I am trying to achieve a multi select drop down menu using options_for_select for this simple app but I can't get it to work.

My model search.rb

class Search < ActiveRecord::Base
def search_books
    books = Book.all
    books = books.where(["market LIKE ?",market]) if market.present?
    return books
end

My search_controller.rb

   def new
     @search = Search.new    
     @markets = Book.uniq.pluck(:market)
   end

My search form

<%= form_for (@search) do |f| %>

  <div class="field">
    <%= f.label :market %><br>
    <%= f.select :market, options_for_select(@markets),:multiple => true, :include_blank => true, :prompt=>'All' %>

My Books Table

create_table "books", force: :cascade do |t|
t.string   "name"
t.string   "market"
t.string   "function"

............................. omitted

With these code, I can get a single select dropdown menu but I need a multi select drop down menu. Thanks

Upvotes: 1

Views: 614

Answers (1)

Ren
Ren

Reputation: 1374

According to the Rails api, the select method takes these arguments:

select(object, method, choices = nil, options = {}, html_options = {}, &block)

:multiple => true is an html option, so it should be the last argument of select

Also I think you don't need both include_blank and prompt, as they serve a similar purpose but are slightly different. See this answer for an explanation of the difference

Therefore try this:

<%= f.select :market, options_for_select(@markets), :prompt=> 'Select all', :multiple => true %>

I'm not able to test this right now, so let me know if that works

Upvotes: 0

Related Questions