Tony
Tony

Reputation: 19171

Ruby Rails collection select is displaying blank "prompt" value?

I have a collection select like the following:

<%= f.collection_select :region_id, Region.find(:all), :id, :name, { :prompt => 'Select a State/Province' }, :style => "width: 200px;" %>

Sometimes the prompt from the :prompt option appears, but sometimes it does not. Does anyone know where I could begin to troubleshoot this? Maybe I have been looking at it too long...

Upvotes: 12

Views: 21418

Answers (5)

Sudhir Vishwakarma
Sudhir Vishwakarma

Reputation: 805

try this <%= f.collection_select :region_id, Region.all, :id, :name, {prompt: 'Select a State/Province'}, {class: "form-control"} %>

Upvotes: 0

robotdana
robotdana

Reputation: 532

:prompt appears in the list when there isn't a selected value.

:include_blank appears in the list always, even if you've loaded the select with a selected value.


if you want your select to always have "Select a State/Province" as the first option:

<%= f.collection_select :region_id, Region.all, :id, :name, include_blank: 'Select a State/Province' %>

if you want your collection to have "Select a State/Province" as the first option only when a region is not already selected:

<%= f.collection_select :region_id, Region.all, :id, :name, prompt: 'Select a State/Province' %>

source: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html

Upvotes: 13

Graeme
Graeme

Reputation:

:include_blank with the value of your blank option seems to do the trick. Try this:

 {:include_blank => "Please select"}

Upvotes: 43

Robin Taylor
Robin Taylor

Reputation: 21

I've been having the same problem. Using 'prompt' seems to create an attribute for the select tag, problem is there is no such attribute that I know of. Plus its clearly not what is described in the Rails docs http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_from_collection_for_select.

Using include_blank seems a good workaround for me.

Cheers, Robin.

Upvotes: 2

nitecoder
nitecoder

Reputation: 5486

Instead of

:prompt => "Select a State/Province"

try

:allow_blank => "Select a State/Province"

EDIT: Yes after checking the API I can see that I had it confused, prompt is the correct way according to the documentation, could it be that it only sometimes it appears because your object has a value already and therefore the prompt is there but it is not the currently selected value in the drop down list???

Upvotes: -1

Related Questions