よく忘れちゃうのでメモ。
select_tagにオブジェクト配列を食わせて、オブジェクトのname属性を表示して、IDを渡すのは常套手段。
というわけで、select_tagでoptions_for_selectを使うのはよくやるんですが、忘れちゃう。
hogeオブジェクトにidとname属性があったとする。
で、hogeオブジェクトの配列がhoge_arrayとして、
select_tag options_for_select(hoge_array.map{ |hoge| [ hoge.name, hoge.id ] } )
角括弧よく忘れるので注意。
nameが前です。valueは後ろね。
Rails APIドキュメントでは改行がうまくいってなくて読みにくいので抜粋。
Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container
where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and
the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values
become lasts. If
selected is specified, the matching "last" or element will get the selected option-tag.
Selected # may also be an array of values to be selected when using a multiple select.
Examples (call, result):
options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
<option value="$">Dollar</option> <option value="DKK">Kroner</option>
options_for_select([ "VISA", "MasterCard" ], "MasterCard")
<option>VISA</option> <option selected="selected">MasterCard</option>
options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
<option value="$20">Basic</option> <option value="$40" selected="selected">Plus</option>
options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
<option selected="selected">VISA</option> <option>MasterCard</option> <option selected="selected">Discover</option>
NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.
PR