views:

56

answers:

3

I have a simple constant called "subjects" in my model Inquire.rb and I like to know if there is a simple way to use the position in the Ruby array rather than making a hash from it with ids or some more complicated array.

Can I do this?

i.e. instead of to_s as it currently does for the value in the select, I would want an integer indicating the position of the question in the array. 1-5 in this case.

Thanks

  SUBJECTS = [ "I have a query about my booking", 
               "I can't find my confirmation email", 
               "I have feedback about a location",
               "I have feedback about your website", 
               "Other enquiry" ]

<%= f.collection_select :subject, Inquire::SUBJECTS, :to_s, :titleize, {:prompt => true} %>

+1  A: 

You can do something like this

<%= select(:inquire, :subject_id, 
      Inquire::SUBJECTS.collect {|x| [x, Inquire::SUBJECTS.index(x) + 1] }) 
%>    

This produces the following HTML

<select id="inquire_subject_id" name="inquire[subject_id]">
  <option value="1">I have a query about my booking</option> 
  <option value="2">I can't find my confirmation email</option> 
  <option value="3">I have feedback about a location</option> 
  <option value="4">I have feedback about your website</option> 
  <option value="5">Other enquiry</option>
</select> 
Steve Weet
A: 

You just need a small helper to do work for you. just like what this build-in helper - http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html

module form_collection_helper
  def options_with_index_for_select(items)
      html = ''
      items.each_with_index { |item, i|  html << "<option value='#{i}'>#{item.titleize}</option>" }
      return html
  end
end

and in your code will just:

<%= f.select :subject, options_with_index_for_select(Inquire::SUBJECTS), {:prompt => true} %>
Jirapong
+1  A: 

Or, you could use the enum_with_index method that's available to you through Enumerable.

<%= f.select :name, Inquire::SUBJECTS.enum_with_index.collect { |s, i| [s.titleize, i] }, {:prompt=>true} %>
vegetables