2019-06-24
家計簿アプリを開発中です。
せっかくなので、搭載した機能とコードについてたまに紹介していきます。
機能:
・月ごとに収入予算と支出予算を設定することができる
・トップページで当月の収入予算と支出予算が表示される。
・今月のその時点での収入額、支出額が表示される。
・収入(支出)予算に対する、その時点での収入(支出)額との差が表示される
・実際の収入額ー実際の支出額で収支状況が分かる。
予算の設定:
設定ページでで年・月を選択し、収入予算額、支出予算額を入力するとDBのbudgetsテーブルにデータが送られます。
コントローラ:
def new
budget = Budget.new
end
def create
@budget = Budget.create(year: budget_params[:year],month: budget_params[:month],
income_amount: budget_params[:income_amount],
spending_amount: budget_params[:spending_amount], user_id: current_user.id)
end
private
def budget_params
params.permit(:year, :month, :income_amount, :spending_amount)
end
end
トップページで当月の収入予算と支出予算を表示:
def index
@name = current_user.name
# 今月は何月か
time = Time.now
this_month = time.month
this_year = time.year
# 設定した予算の今月
@income_budget = Budget.find_by(year: this_year, month: this_month).income_amount
@spending_budget = Budget.find_by(year: this_year, month: this_month).spending_amount
まず、今が何年の何月かリアルタイムで認識される必要があります。
現在、this_yearには今年("2019")が、this_monthには今月("6")が入るようになっています。それを使いbudgetsテーブルから「年」は今年「月」は今月の「(設定した)収入予算額」を条件に検索して取得します。支出予算も同様です。
取得した値をビューファイルに」渡して表示させます。
今月のその時点での収入額、支出額を表示:
# 今月の現在の収支状況
@current_income = Income.group("YEAR(date)").group("MONTH(date)").sum(:amount)
@current_income[[this_year,this_month]]
@current_income_view = @current_income[[this_year,this_month]]
@current_spending = Spending.group("YEAR(date)").group("MONTH(date)").sum(:amount)
@current_spending[[this_year,this_month]]
@current_spending_view = @current_spending[[this_year,this_month]]
end
コードが長くなってしまいました。
まず、カラムの型が予算テーブルと異なっているので検索の仕方を変えました。(DB設計は反省です)。
incomeテーブルで検索条件を「年」を今年「月」を今月とし、その対象のレコードのincome_amount(収入金額)の合計金額を取得します。この時点では{2019,6 => 300000)という形で取得できていますので、そのまま@current_spending2019,6とすれば300000が取れます。しかし、毎月リアルタイムで値を取りたいので@current_spendingthis_year,this_monthに置き換えています。こうすれば7月に入れば、自動的に7月のものをデータベースから探してきます。
ポイントは、日付を検索する際はcreated_atではなく専用で作ったdateから探してきます。なぜなら、検索対象は「入力を行った日」ではなく「入力欄に入力された日付(中身)」だからです。(カレンダーから選べるようになっています)。
例えば、6月1日に思い出して5月31日の分を入力することも考えられるため、その際齟齬が生じないよう、DB設計と検索条件を考えました。
・収入(支出)予算に対する、その時点での収入(支出)額との差
・実際の収入額ー実際の支出額で収支状況が表示される。
ビューファイル:
.side-contents
.side-contents_budget
.side-contents_budget_income
今月の収入予算
= @income_budget.to_s(:delimited)
円
.current_income
現在の状況
= @current_income_view.to_s(:delimited)
円
.income_difference
差額
= (@income_budget-@current_income_view) * -1
-# 収入予算より実績が上回っていたら計算式ではマイナスだが、会計上はプラスなので*-1して反転
円
.side-conyents_budget_spending
今月の支出予算
= @spending_budget.to_s(:delimited)
円
.current_spending
現在の状況
= @current_spending_view.to_s(:delimited)
円
.spending_difference
差額
= @spending_budget-@current_spending_view
円
.total
収支
= @current_income_view - @current_spending_view
円(今月の収入額-今月の支出額状況)
デザインはまだ仮置きなので
hamlは簡易的ですが、ここではただ四則演算で差額を計算しています。収入予算に対する、実際の収入額は予算を超えていれば計算上マイナスになるますが会計上はプラスなので*(-1)してプラスとマイナスを反転させています。
(まあ反対に実際額から予算を引いても同じことですが...)