maeshimaの日記

メモ書きです

railsでselectタグを出力するヘルパー

メモ

option

include_blank

trueなら空白のoptionタグが作られる

prompt

値が空白のoptionで表示される文字列を指定。include_blankとは共存できないっぽい

index

出力結果のindexを指定できる

disabled

disabled optionを出力する

select

利用例

select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })

出力結果

<select name="post[person_id]">
  <option value=""></option>
  <option value="1" selected="selected">David</option>
  <option value="2">Sam</option>
  <option value="3">Tobias</option>
</select>

collection_select

モデルのコレクションからselectタグを作るメソッド。formで指定したモデルオブジェクト以外のモデルからselectの要素を作る時などに使える。

collection_select(属性名, collection, value_method, text_method)

collection_select("category_id", Category.find(:all), :id, :name)

options_from_collection_for_select

collection_selectからselectタグを抜いたもの。