見出し画像

【Rails】date_select のそれぞれのフォームにclassを設定する

Railsのviewで、日付選択フォームを表示する際、多くの場合はdate_fieldもしくはdate_selectを使うことになると思います。

date_selectはデフォルトだとデザインが寂しい感じなので、デザインを変更したいなーと思いますが、変更するのがなかなか難しいと感じます。

そこで、デザインを変更する際には、classを設定しますが、
それぞれのフォームごと(年、月、日ごと)のclassを設定したいとなった時に、少し詰まったので方法を簡単にまとめました。

個別にcssを設定する方法

普通にclassを設定しようとすると、「class:"クラス名"」のように記載すると思いますが、これだと全てのフォーム共通のclassになります。

(ちなみにこの際の注意なのですが、下記のように記載してもclassは設定されません。

<%= f.date_select(:birthday, class: "クラス名") %>

下記のような感じで、第四引数として{}で囲ってclassを設定する必要があります。

<%= f.date_select(:birthday , {}, {class: "クラス名"}) %>

間に空の{}があるのは第三引数の{}です。classを第四引数として認識させるにはこのように空でも第三引数を記載する必要があります)

本題に戻りますが、上記の方法だと共通のclassは設定できますが、個別の設定はできません。
フォーム個別(年、月、日ごと)にclassを設定するには「with_css_classes」オプションを使います。

https://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-date_select

>:with_css_classes
- Set to true or a hash of strings. Use true if you want to assign generic styles for select tags. This automatically set classes 'year', 'month', 'day', 'hour', 'minute' and 'second'. A hash of strings for :year, :month, :day, :hour, :minute, :second will extend the select type with the given value. Use html_options to modify every select tag in the set.

-(https://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-date_select)より引用

使い方は、第三引数に「with_css_classes: true」を設定します。

<%= f.date_select(:birthday, {with_css_classes: true}) %>

すると、ブラウザの検証ツールで確認すると分かるのですが、下記のように、「year、month、day」(with_css_classes: trueとした場合)とclassが個別につけられるようになります。

<select id="〇〇_birthday_1i" name="〇〇[birthday(1i)]" class="year"></select>
<select id="〇〇_birthday_2i" name="〇〇[birthday(2i)]" class="month"></select>
<select id="〇〇_birthday_3i" name="〇〇[birthday(3i)]" class="day"></select>

ここで注意なのが、「with_css_classes: true」を記載するのは第四引数ではなく、第三引数であるということです。

共通のclassを設定する場合は、第四引数に記載しますが、
これは「class: "クラス名"」と書く場合です。

共通でつけたい場合は、このように第四引数に記載でOKなのですが、
フォーム個別、つまり「with_css_classes: true」を使う際には、classではなくオプションなので第三引数に書くという点に注意です。

補足:フォーム共通のcssについて

先ほど記載した通り、共通のclassを設定したいときは、第四引数に「class:"クラス名" 」みたいな形で記載すれば良いのですが、cssファイルで下記のように記載することでも共通の指定はできます。

.year,.month,.day{ 
	width: 100px;
}


参考

https://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-date_select
https://qiita.com/Nosuke0808/items/357adc0a254f5252d5b9


この記事が気に入ったらサポートをしてみませんか?