How to have a drop down code will go in _form.html.erb but where will that select("Contact",) code go ? – iCyborg Jan 01 '13 at 19:01

4

In your model,

class Contact
  self.email_providers = %w[Gmail Yahoo MSN]
  validates :email_provider, :inclusion => email_providers
end

In your form,

<%= f.select :email_provider, 
    options_for_select(Contact.email_providers, @contact.email_provider) %>

the second arg of the options_for_select will have any current email_provider selected.

konyak
  • 10,818
  • 4
  • 59
  • 65
0

I wanted to display one thing (human readable) but store another (an integer id).

Small example

Here's a small example that helped:

<%= form.select(:attribute_name, {cat: 5, dog: 3} )%>

The {cat: 5, dog: 3} will display "cat" and "dog", but save 5 and 3.


Real world example

Here's the actual use case. It displays the names of sellers (that humans can read), but saves the sellers' id (an integer):

<div class="field">
  <%= form.label :seller_id %>
  <%= form.select :seller_id, seller_names_and_ids(), {include_blank: true}, {required: true, class: "form-control"} %>
</div>

And the helper is defined as:

def seller_names_and_ids
  # We want this to produce a hash of keys (the thing to display) and values (the thing to save, 
  # in thise case the seller_id integer)
  sellers = Seller.all
  h = {}
  sellers.each do |seller|
    thing_to_display = seller.name + " (" + seller.id.to_s + ")"
    thing_to_save_in_db = seller.id
    h.store(thing_to_display, thing_to_save_in_db) 
  end
  h
end
stevec
  • 41,291
  • 27
  • 223
  • 311