Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails how can I implement a HTML select menu using an Array of Strings?

I have a FinancialDocument#document_type model attribute. I'd like to let the user select the document type from an HTML select menu populated by an Array of Strings...

doctypes = [ 'Invoice', 'Packing slip', 'Other' ]

For each option, the displayed label and returned value would be identical.

I looked at the select and collection_select helpers, but they seem geared toward selecting a child model, not merely a String value. I couldn't discover how to bend them to my purpose.

Here's how I'm trying to do it (I'm using Haml, not Erb)...

form_for(@financial_document) do |f|
  - doctypes = [ 'Invoice', 'PS', 'Packing slip', 'Other' ]
  = f.collection_select @financial_document, :document_type, \
      doctypes, :to_s, :to_s, :include_blank => true

I get this error...

undefined method `merge' for :to_s:Symbol

Is there a different helper that I could use for this? Or a way to use select or collection_select?

like image 295
Ethan Avatar asked Jun 27 '09 16:06

Ethan


2 Answers

Is doctypes an ActiveRecord collection? Looking at the code it doesn't seems so. You can use the select helper.

= f.select :document_type, doctypes, :include_blank => true

Also, you don't need to pass @financial_document if you call the tag on the form object created with form_for.

like image 182
Simone Carletti Avatar answered Nov 13 '22 03:11

Simone Carletti


doctypes.map!{|d| [d]}
f.select(@financial_document, :document_type, doctypes)

will do it I think.

like image 21
Ben Hughes Avatar answered Nov 13 '22 04:11

Ben Hughes