Chosenはセレクトボックスをかっこよくしてくれる。
Railsのためにchosen-railsというgemもある。Railscastsにわかりやすいスクリーンキャストがある。
問題
current_user.storiesの中からstoryを選択し、そのidをnext_story_idに入れるというセレクトボックスを作ろうとして、_form.html.erbに
_form.html.erb
<%= f.collection_select :next_story_id, current_user.stories, :id, :title %>
というviewのhtml.erbを書いたのだが、chosenはデフォルトで、最初に登場する選択肢(current_user.storiesで一番idが小さいやつ)を選んだ状態になってしまう。さらに、編集して保存したあと、もういちど編集しようとすると、editページに来たとき、selectはデフォルトで、やはり最初に登場する選択肢を選んだ状態になってしまう。
解決策
collection_selectメソッドを使わずに、options_from_collection_for_selectメソッドを使って、
_form.html.erb
<select name="story[next_story_id]" id="story_next_story_id">
<option value="">なし</option>
<%= options_from_collection_for_select current_user.stories, :id, :title, @story.next_story_id || "" %>
</select>
としたらうまくいった。デフォルトではvalue=""の「なし」を選択した状態だし、もしすでに@story.next_story_idがある場合、それを選択した状態になる。ちなみにCoffeeScriptは
story.js.coffee
$('#story_next_story_id').chosen()
と書いておいた。