おぴよの気まぐれ日記

おぴよの気まぐれ日記

岡山やプログラミング、ファッションのこと、子育てや人生、生き方についての備忘録。

【Rails】簡単にformが作成できるsimple_form

Ruby on Railsで登録機能や更新機能を作る際に必要なform。

このformの作成を簡単に作成することが出来る便利なライブラリ「simple_form gem」のご紹介。

simple_formで作った問い合わせform画面のイメージ
simple_formで作った問い合わせform画面のイメージ

インストール手順

Gemfileに追加して、bundle installする。

gem 'simple_form'

モデルの作成

generateコマンドを使ってモデルを作ります。

$ bundle exec rails g model hoge name:string age:integer gender:string birthday:date email:string

rake db:migrateしてDBにテーブルを作成します。

$ bundle exec rake db:migrate

こちらで作成したhogesテーブルです。

 Table "public.hoges"
   Column   |            Type             | Collation | Nullable |              Default              
------------+-----------------------------+-----------+----------+-----------------------------------
 id         | bigint                      |           | not null | nextval('hoges_id_seq'::regclass)
 name       | character varying           |           |          | 
 age        | integer                     |           |          | 
 gender     | character varying           |           |          | 
 birthday   | date                        |           |          | 
 email      | character varying           |           |          | 
 created_at | timestamp without time zone |           | not null | 
 updated_at | timestamp without time zone |           | not null | 
Indexes:
    "hoges_pkey" PRIMARY KEY, btree (id)

コントローラーの作成

newアクションはモデルをnewしてオブジェクトする。

class HogesController < ApplicationController
  def index
  end

  def new
    @hoge = Hoge.new
  end
end

createアクションは今回は割愛します...

画面の作成

form_tagの代わりにsimple_form_forを使います。

ざっくり使い方

# haml
.hoges__new
  .hoges__new-title
    %h2
      新規登録画面
    %p
      ご依頼・お問い合わせなどございましたら、下記よりお気軽にご連絡ください。
  .hoges__new-form
    = simple_form_for(@hoge, url: hoges_path) do |f|
      = f.input :name
      = f.input :age
      = f.input :birthday
      .hoges__new-form-btn
        = f.submit

# html
<div class="hoges__new">
  <div class="hoges__new-title">
    <h2> 新規登録画面 </h2>
    <p> ご依頼・お問い合わせなどございましたら、下記よりお気軽にご連絡ください。 </p>
  </div>
  <div class="hoges__new-form">
    <form class="simple_form new_hoge" id="new_hoge" novalidate="novalidate" action="/hoges" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="6VTA5orkwF0ot26n+iZKp6+OeokxeTOxTnAm79HSX1RFx9LM9OMnevbi1HP7YoCl3cjJGrAa24rGhf6NFIRb0Q==">
      <div class="form-group string optional hoge_name"><label class="control-label string optional" for="hoge_name">お名前</label><input class="form-control string optional" type="text" name="hoge[name]" id="hoge_name"></div>
      <div class="form-group integer optional hoge_age"><label class="control-label integer optional" for="hoge_age">ご年齢</label><input class="form-control numeric integer optional" type="number" step="1" name="hoge[age]" id="hoge_age"></div>
      <div class="form-group date optional hoge_birthday"><label class="control-label date optional" for="hoge_birthday_1i">誕生日</label>
        <select id="hoge_birthday_1i" name="hoge[birthday(1i)]" class="form-control date optional">
          <option value="2014">2014</option>
          <option value="2015">2015</option>
          <option value="2016">2016</option>
          <option value="2017">2017</option>
          <option value="2018">2018</option>
          <option value="2019" selected="selected">2019</option>
          <option value="2020">2020</option>
          <option value="2021">2021</option>
          <option value="2022">2022</option>
          <option value="2023">2023</option>
          <option value="2024">2024</option>
        </select> 
        <select id="hoge_birthday_2i" name="hoge[birthday(2i)]" class="form-control date optional">
          <option value="1">1月</option>
          <option value="2">2月</option>
          <option value="3">3月</option>
          <option value="4">4月</option>
          <option value="5">5月</option>
          <option value="6">6月</option>
          <option value="7">7月</option>
          <option value="8">8月</option>
          <option value="9" selected="selected">9月</option>
          <option value="10">10月</option>
          <option value="11">11月</option>
          <option value="12">12月</option>
        </select> 
        <select id="hoge_birthday_3i" name="hoge[birthday(3i)]" class="form-control date optional">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
          <option value="6">6</option>
          <option value="7">7</option>
          <option value="8">8</option>
          <option value="9">9</option>
          <option value="10">10</option>
          <option value="11">11</option>
          <option value="12">12</option>
          <option value="13">13</option>
          <option value="14">14</option>
          <option value="15">15</option>
          <option value="16">16</option>
          <option value="17">17</option>
          <option value="18">18</option>
          <option value="19">19</option>
          <option value="20">20</option>
          <option value="21">21</option>
          <option value="22">22</option>
          <option value="23">23</option>
          <option value="24">24</option>
          <option value="25" selected="selected">25</option>
          <option value="26">26</option>
          <option value="27">27</option>
          <option value="28">28</option>
          <option value="29">29</option>
          <option value="30">30</option>
          <option value="31">31</option>
        </select> 
      </div>
      <div class="hoges__new-form-btn"> <input type="submit" name="commit" value="登録する" data-disable-with="登録する"></div>
    </form>
  </div>
</div>

formの種類

simple_formの便利なところでカラムの型に応じてformの種類の自動で判断し生成してくれます。

  • string型: テキストフィールド
  • integer型: 数値フィールド
  • date型: 年月日のセレクトボックス
  • boolean型: チェックボックス
# テキストフィールドの表示
= f.input :name

# ラジオボタンの表示
= f.input :inquiry_type, as: :radio_buttons

# セレクトボタンの表示
class User
  GENDERS = %w(男性 女性 性別無回答).freeze
end
= f.input :gender, collection: User::GENDERS, label: false, hint: '感想レビューに表示されます'

# hidden項目
= f.input :not_delivery, as: :hidden, input_html: { value: false }

# ボタンの表示
= f.submit class: 'btn btn-primary', data: {disable_with: t('text.disable_with')}

便利な機能

simple_formで作った問い合わせform画面のイメージ
simple_formで作った問い合わせform画面のイメージ

# ラベル名の変更(label)
= f.input :email, label: false
= f.input :email, label: 'メールアドレス'

# 未入力時に表示する文字列(placeholder)
= f.input :email, placeholder: 'メールアドレス'

# classやidを指定する(class, id)
= f.input :email, class: 'form-control'

# 備考欄を表示する(hint)
= f.input :tel, hint: '半角数字、-(ハイフン)'

# セレクトボタンで初期選択を空にする
= f.input :birthday, start_year: Date.current.year - 100, end_year: Date.current.year - 10, include_blank: true
 ※初期文字列を表示したい時は文字列を設定して下さい。

日本語化

ラベル名の部分など所々デフォルトだと英語表示されますが、これらは「i18n」というgemを利用すると日本語表示することが可能です。

# config/locales/ja.yml
ja:
  activerecord:
    attributes:
      hoge:
        name: 'お名前'
        age: 'ご年齢'
        birthday: '誕生日'

こんな感じでja.ymlファイルを作成しモデル名とカラム名に紐づく日本語を定義しておくと自動で日本語表示されます。 色々なことが出来るので、これはまた別の記事でまとめたいと思います。