LoginSignup
6
6

More than 5 years have passed since last update.

Chosen-railsで、初期状態(デフォルト)を設定する方法

Posted at

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()

と書いておいた。

6
6
0

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
6
6