LoginSignup
4
4

More than 5 years have passed since last update.

Railsのcolor_fieldの使い方

Posted at

概要

Railsのビューヘルパーにcolor_fieldというものがある。
使い方を調べてもあまり情報がなかったので自分なりのメモ。


form.html.erb
<%= f.color_field :color %>

このようにすることで色を選択できるようになり、
選択した色のカラーコードが送られる。
(colorというカラムがあるものとする)

+----+--------+------+-------------------------+-------------------------+---------+
| id |        |      | created_at              | updated_at              | color   |
+----+--------+------+-------------------------+-------------------------+---------+
|    |        |      |                         |                         | #ff8000 |
+----+--------+------+-------------------------+-------------------------+---------+

このようにカラーコードが保存されていることが確認できる。
あとはそれをテンプレート側で、、、

sample.html.erb
<div style="background-color:<%= @article.color %>">

少し強引な気もするがbackground-colorは選択した色になっている。

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