0

I'm trying to select multiple events in the invtime form.

Invtime

has_many :events

This is my form code:

    <%= f.select :event_id, Event.all.collect {|x| [x.title, x.id]}, {}, :multiple => true %>

The display looks good! But, when I select the last event and submit, I get:

undefined method `to_i' for ["", "62"]:Array

The page inspection shows:

<select id="invtime_event_id" multiple="multiple" name="invtime[event_id][]">
  <option value="66">Meeting</option>
  <option value="62">Auto fill some fields on new workorder</option>
</select>

Thanks for the help!

Reddirt
  • 5,913
  • 9
  • 48
  • 126
  • Can you post the stacktrace of the error please? (and eventually the corresponding line raising the error) --- Also, shouldn't you be using `f.select :event_ids` (plural) since it is a multiple select? – MrYoshiji Oct 18 '13 at 18:38

2 Answers2

0

undefined method `to_i' for ["", "62"]:Array

from the docs:

:include_blank - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element.

So try adding include_blank: true

<%= f.select(:event_id, Event.all.collect {|x| [x.title, x.id]}, {}, :multiple => true, include_blank: true ) %>

also, you might try collection_select, where @events = Event.all

<%= f.collection_select(:event_id, @events, :id, :title, include_blank: true ) %>
dax
  • 10,779
  • 8
  • 51
  • 86
  • Hi dax, I'm pretty sure `include_blank` has nothing to do with this problem, the error comes from trying to convert a blank title to an integer for the select value. Your collection select suggestion is a good one, but there's no need to create extra overhead by adding a temporary variable - just use `Event.all` in the helper itself. – Matt Oct 18 '13 at 18:51
  • `include_blank` would fix that, though, right? If it isn't necessary, you're right, it should be removed - but how does just using `collection_select` remedy that? There's an object for `x` in OP, otherwise there wouldn't be an `x.id` of 62. Thanks for your comment! – dax Oct 18 '13 at 18:58
0

The select helper doesn't know what to do with a collection like that, it assumes the first value is an ID and the second a string, you might be able to just reverse your method calls but this isn't really the right way to create a select tag, instead either use collection_select as dax suggests or use the options_from_collection_for_select helper:

<%= f.select :event_id, options_from_collection_for_select(Event.all, :id, :title), {}, :multiple => true %>
Community
  • 1
  • 1
Matt
  • 13,948
  • 6
  • 44
  • 68