13
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsのselect_tagで選択された状態で表示したい

Posted at

現状

メモアプリを作成しています。各メモにはカテゴリーが設定できるようにしました。 select_tagを使ってプルダウンリストを作成できたのですが、編集画面のカテゴリー欄にはプルダウンリストの一番上のものが表示されています。 これをすでに設定済みのカテゴリーが表示されるようにしたい。

現状のコード

```edit.html.erb <%= select_tag 'memos[category_id]', options_from_collection_for_select(@categories, :id, :name), id:"form-category", class:"form-control" %> ```

解決策

{ :selected => @memo.category_id.to_i }を追加する。

追加後のコード

```edit.html.erb <%= select_tag 'memos[category_id]', options_from_collection_for_select(@categories, :id, :name, { :selected => @memo.category_id.to_i }), id:"form-category", class:"form-control" %> ```
13
5
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
13
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?