user6107987
user6107987

Reputation:

Include custom id and value in Rails collection_select besides the normal prompt: or :include_blank?

Include custom id and value in Rails collection_select besides the normal prompt: or :include_blank?

<%= f.collection_select :id, @events, :id, :date_formatted, { prompt: "Select..." } %>

produces:

<select name="event[id]" id="event_id">
<option value="">Select...</option>
<option value="16">26.06.15</option>
<option value="11">07.06.15</option>
<option value="20">11.05.15</option>
<option value="1">30.11.14</option>
<option value="14">26.07.14</option>
<option value="10">27.02.13</option>
<option value="2">11.12.12</option>
<option value="19">26.06.12</option>
<option value="8">10.06.12</option>
<option value="4">21.08.11</option>
<option value="15">26.04.11</option>
<option value="12">14.02.11</option>
<option value="13">04.12.10</option>
<option value="7">06.11.10</option>
<option value="18">05.10.10</option>
<option value="6">30.01.10</option>
<option value="17">08.03.09</option>
<option value="5">20.01.09</option>
<option value="9">04.11.08</option>
<option value="3">24.04.08</option>
</select>

I want to include my own:

<option value="something">Whatever</option>

Documentation not helping.

Upvotes: 3

Views: 410

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14890

You can take advantage of the OpenStruct data structure.

An OpenStruct is a data structure, similar to a Hash, that allows the definition of arbitrary attributes with their accompanying values. This is accomplished by using Ruby’s metaprogramming to define methods on the class itself.

I presume you have something like this in your controller.

@events = Event.where(...)

You can then do this in your controller instead.

@events = [OpenStruct.new(id: 'something', date_formatted: 'some_other_value')]
@events << Event.where(...)
@events.flatten!

And then just like before in your view. Everything in @events now responds to date_formatted

Upvotes: 2

Related Questions