0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails 掃除提案アプリのアルゴリズム

Posted at

はじめに

オリジナルアプリとして掃除提案アプリを開発しました。その際、苦労したところを忘れずに書き記します。

目次

1.掃除提案機能の説明
2.必要なカラムとその型
3.Rubyのコード

1.掃除提案機能の説明

予め掃除箇所の情報を登録する。登録情報に応じて、毎日どこを掃除すれば良いか提案する機能である。なお登録情報は下記3つ。
・掃除箇所名
・掃除頻度(○日に一回掃除する)
・最後に掃除した日付

提案のアルゴリズムとしては下記の通り。
①最後に掃除した日付と今日の日付から経過日数を算出する
②経過日数と掃除頻度を比較する
③結果に応じてtrueもしくはfalesを返す。
④falseとなった場合、提案(画面に表示)する。

2.必要なカラムとその型

必要なカラムと型を下記に示す。状態は上記のtrueもしくはfalseが入るboolean型のカラムである。

登録情報 カラム名
掃除箇所 place string
清掃期間 period_cleaning integer
最後に清掃した日付 last_cleaned_date date
状態 status boolean

マイグレーションファイルの記述も下記に示す。

2020***********_create_suggestions.rb
class CreateSuggestions < ActiveRecord::Migration[6.0]
  def change
    create_table :suggestions do |t|
      t.string :place, null: false
      t.integer :period_cleaning, null: false
      t.date :last_cleaned_date, null: false
      t.boolean :status, null: false
      t.timestamps
    end
  end
end

3.Rubyのコード

改めて提案のアルゴリズムを下記に示す。
①最後に掃除した日付と今日の日付から経過日数を算出する
②経過日数と掃除頻度を比較する
③結果に応じてtrueもしくはfalesを返す。
④falseとなった場合、提案(画面に表示)する。

①〜④までのコードを下記のようにした。はじめにフォームから送られた掃除箇所の情報をインスタンス変数に代入する。次に変数this_dayに今日の日付を代入する。ここから①の経過日数を算出する(3行目:this_day - @suggestion.last_cleaned_date)。最後に掃除頻度(@suggestion.period_cleaning)to
経過日数(num_days)を比較し、trueもしくはfalseを状態(status)に代入する。

def create
  @suggestion = Suggestion.new(suggestion_params) #suggestion_paramsはストロングパラメータ
  this_day = Date.today
  num_days = (this_day - @suggestion.last_cleaned_date).to_i
  @suggestion.status = !(@suggestion.period_cleaning <= num_days)
end

以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?