LoginSignup
36
30

More than 5 years have passed since last update.

collection_selectタグでclassが反映されない

Last updated at Posted at 2014-08-11

ちょっとハマったのでメモ。

_form.html.erb
<%= f.collection_select(:target, code.all, :code_no, :code_value, {class: "form-control input-sm"}) %>

リファレンスに従ってcollection_selectにclassオプションを指定しても、出力されるHTMLに指定したclassが出力されない。。。

StackOverflowを見て解決しました。

_form.html.erb
<%= f.collection_select(
        :target_id, code.all, :code_no, :code_value,
        {prompt: ""}, {class: "form-control input-sm"}) %>

promptを渡してあげることで無事classが出力されました。

promptとは?

promptオプションとは値が未設定の時にリストの先頭に値を表示するかどうかを制御するオプション。
値を渡した場合はそれが初期値となるらしい。

試しに、上記コードで「{prompt: ""}」としていた箇所を、「{prompt: true}」としてみると、
「Please Select」という値が初期値として表示されました。
逆に、「{prompt: "false"}」とすると、リストの1行目が初期表示されました。
classがcollection_selectの場合は第7引数、f.collection_selectの場合は第6引数としてclassが渡されればOKのようですね。

参考

36
30
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
30