8
16

More than 3 years have passed since last update.

Form_forでプルダウンメニューの項目をDBから選択する

Last updated at Posted at 2019-07-04

概要

select_tagによる、決め打ちの選択肢 ↓
<%= f.select :subject, [["1", "1"], ["2", "2"]] , class:"form-control" %>
ではなく、DBのテーブルから項目を引っ張ってきたい時 :fist_tone4:

今回の例

都市を入力するページで、国をプルダウンで選択させたい。
Countries (国のテーブル) ※数が増えることがないのでdb/*seed.rbに記載済み。

id name
1 Australia
2 Canada
3 Japan

has_many :cities
国は都市をたくさん持っています。

Cities (都市のテーブル):tokyo_tower: :shinto_shrine: :metro:

id name country_id
1 Tokyo 3
2 Osaka 3
3 Kyoto 3

belongs_to :countries

collection_select を使う

app/views/cities/new.html.erb

<%= form_for @city do |c| %>
<%= c.label :country_id %>
<%= c.collection_select :country_id, Country.all, :id, :country_name %>

collection_selectの文法

<%= f.collection_select <属性名>, <プルダウンメニュー表示用の配列データ>, <valueとして扱うカラム名>,  <表示用のカラム名>, <オプション> %>

オプション

:prompt

prompt オプションを使うと、プルダウンメニューが選択されていない時に設定した文字列の行が先頭に追加される。

<%= form_for @city, url: admins_cities_new_path do |c| %>
       <%= c.label :country_id %>
       <%= c.collection_select :country_id, Country.all, :id, :country_name,
                               :prompt => "国を選択" %>

これで選択していない時は、 国を選択が表示される :fist_tone4:

:include_blank

プルダウンメニューの先頭に空白行を追加する。空白行の value は空文字列が指定される。
include_blank オプションの値を true/false ではなく文字列にすると、その文字列が使用される。

<%= f.collection_select :origin_id, Origin.all, :id, :name, :include_blank => true %>
8
16
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
8
16