12
12

More than 3 years have passed since last update.

【Rails / MySQL】データ型をintegerからfloatへ変更しnumber_fieldで小数点を扱えるようにする

Last updated at Posted at 2020-01-03

前回の記事の続きで初めてfloat型を扱ったのでメモ

やりたい事

  • DBに間違ってinteger型で作ったカラムをfloat型に変更
  • form_for内でnumber_fieldで小数点を扱えるようにする
  • DBに保存した値を合計するメソッドを作る

参考

【Rails】form_for の number_field で小数を入力できるようにする
https://qiita.com/tegnike/items/07f789eb22c7a7bf6a19

マイグレーションを使ったカラムの追加、削除、データ型の変更 [ 自分用メモ ]
https://qiita.com/dawn_628/items/13fa64dc6d600e921ce3

【Rails】カラムの合計値を求める!
https://qiita.com/tomokichi_ruby/items/8758a91566957cfc5429

number_fieldでは整数のみしか扱えない

new.html.erb
<%= form_for @count_time do |f| %>
 <%= f.number_field :count_hour, class:'input_form' %>
 <%= f.submit '登録', class:'input_submit' %>
<% end %>

スクリーンショット 2020-01-03 17.33.24.png

というフォームがあって,

小数点の数字をいれると,
スクリーンショット 2020-01-03 17.35.00.png
というふうになるので

new.html.erb
<%= form_for @count_time do |f| %>
 <%= f.number_field :count_hour, step: '0.1', class:'input_form' %>
<%# step: '0.1'を追加 %>
 <%= f.submit '登録', class:'input_submit' %>
<% end %>

step: '0.1'を追加すると小数点以下第一位までの数値を扱えるようになります

このままだとDBには整数でしか保存されない

DBの count_hourinteger型なので整数のみしか保存してくれないのでカラムの型を変更する

ターミナル
$ rails g migration change_data_count_hour_to_count_time
Running via Spring preloader in process 94544
      invoke  active_record
      create    db/migrate/20200103074431_change_data_count_hour_to_count_time.rb

カラム名がcount_hourでテーブル名がcount_timeになります

20200103074431_change_data_count_hour_to_count_time.rb
class ChangeDataCountHourToCountTime < ActiveRecord::Migration[5.2]
  def change
    change_column :count_times, :count_hour, :float #追記。テーブル名は複数形で
  end
end

rails db:migrateします

これでfloat型に変更できたのでnumber_fieldから送られる小数点の値がDBへ保存できるようになりました

DBの値をビューへ描画

index.html.erb
  <table>
    <tr>
      <th>日付</th>
      <th>時間</th>
    </tr>
    <% @count_time.each do |count_time| %>
      <tr>
        <td><%= count_time.created_at.to_date %></td>
        <td><%= count_time.count_hour %>時間</td>
      </tr>
    <% end %>
  </table>

スクリーンショット 2020-01-03 17.50.13.png

sumメソッドを使い学習時間の合計を表示させる

count_time_controller.rb
class CountTimesController < ApplicationController
 def index
  @count_time = CountTime.where(user_id: current_user.id).order('updated_at DESC').limit(5)
  @count_hour = @count_time.sum(:count_hour)
 end
end

sumメソッドの引数にカラムを指定するで合計値を出します

完成

スクリーンショット 2020-01-03 18.04.07.png

まとめ

ひとまずこれで自分が最初に想像していた主要機能が完成しました。開発にそんな時間がかからないアプリでしたが知らない事も学べたので良かったかなと。あとは思い付いた追加の機能を開発していこうと思います。

終わり

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