Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f.collection_select not displaying the selected value

There are so many results for this search on google, and it's even asked at SO - but the solutions discussed so far are not helping me. Here's the issue: I have a form_for @company |f| and I am using f.collection_select for company_status_id - but when the form loads, I want the actual company status selected if it is set. Through the debugger I know, that it's been set, yet I am getting a default value displayed there. Here's the code:

= puts @company.company_status_id
= f.collection_select :company_status_id, ListCache.company_statuses, :id, :name, {:prompt => @select_value}

Here's the generated htmnl

<select id="company_company_status_id" prompt="-Select-" name="company[company_status_id]">
<option value="1">-Not Available-</option>
<option value="2">Active</option>
<option value="3">Bankrupt</option>
<option value="4">Acquired</option>
</select>

And the conditions remain the same even if I do:

f.collection_select :company_status_id, ListCache.company_statuses, :id, :name, {:prompt => @select_value, :selected => :selected => @company.company_status}

Or

f.collection_select :company_status_id, ListCache.company_statuses, :id, :name, {:prompt => @select_value, :selected => @company.company_status}
like image 647
Saad Rehman Shah Avatar asked Apr 19 '12 10:04

Saad Rehman Shah


4 Answers

If you use collection_select helper, syntax is very simple:

<%= f.collection_select :category_id, Category.all, :id, :name,
                       prompt: true, selected: @product.category_id %>

I hope this help

like image 172
Raf Avatar answered Nov 13 '22 00:11

Raf


Sometimes you just need to go to the browser address bar and press enter. Normal reloading the page clicking the refresh button doesn't help. My problem was solved that way.

like image 37
zawhtut Avatar answered Nov 13 '22 00:11

zawhtut


This is what I finally did:

f.collection_select :company_status_id, ListCache.company_statuses, :id, :name, {:prompt => @select_value, :selected => @company.company_status_id.to_i}

I read on of the answers on a similar question that collection_select automatically selects the selected value by making comparisons of what is passed with the attributes of collection. apparently there was a difference of their types, and comparing the int from CompanyStatus to the int of @company.company_status_id.to_i worked out. Though @company.company_status_id is supposed to be int as well. I can see that in the db. Anyway, it this line of code worked.

If anyone can exaplain, I will be much thankful!

like image 20
Saad Rehman Shah Avatar answered Nov 12 '22 23:11

Saad Rehman Shah


<% form_for(@company) do |f| %>
   <%= f.select(:company_status_id, ListCache.all.map {|lc| [lc.name, lc.id]} ) %>
<% end %>
like image 2
TomDunning Avatar answered Nov 12 '22 23:11

TomDunning