ANUP
ANUP

Reputation: 185

Using options_from_collection_for_select

I am trying to use

options_from_collection_for_select(collection, value_method, text_method, selected = nil)

But I am unable to pass proper parameter to it. What should be type on collection element? (Sample for complete usage will be helpful)

I have to use it with format like Name=AL and ID=23, like it is State name and it Code.

So for using how should I provide the collection object to it.

I have tried with Hash, Map and Array

Upvotes: 0

Views: 7712

Answers (2)

sxx1728
sxx1728

Reputation: 1

I think, you can try options_for_select.

options_for_select([text1, value1], [text2, value2]])

Upvotes: 0

KARASZI István
KARASZI István

Reputation: 31467

The 1st parameter of options_from_collection_for_select should be an arbitrary collection (accuratley any objects which has a map method), for example an Array.

Example with Array of Hashes:

options_from_collection_for_select([ { :id => 1, :name => 'Foo' }, { :id => 2, :name => 'Bar' } ], 'to_s', 'to_s')

Of course this is a stupid example, because the 2nd parameter is the method for the value and the 3rd is the method of the name. So the method will call the to_s methods on the Hash items to fetch the id and value for the <option/>, so this will produce:

'<option value="{:id=&gt;1, :name=&gt;&quot;Foo&quot;}">{:id=&gt;1, :name=&gt;&quot;Foo&quot;}</option>\n<option value="{:id=&gt;2, :name=&gt;&quot;Bar&quot;}">{:id=&gt;2, :name=&gt;&quot;Bar&quot;}</option>'

If you provide proper objects, for example ActiveRecord::Base objects:

options_from_collection_for_select(Article.all, 'id', 'title')

It will produce a better output:

'<option value="28">FooBar</option>\n<option value="29">BarFoo</option>'

Upvotes: 2

Related Questions