ポートフォリオの家計簿アプリ作成中、非常に躓いた箇所がありましたので備忘録として書いていきます。
何に躓いたかというと、同じところで5回連続エラーが起こったのです。
※3~4日ほどでやっと解消できました😊
今回はエラーの内容と、それを解決した方法をそれぞれ書いていきます。
苦悩の連続の全てはここから始まりました。
まず、エラー画面はでていないのですが、
投稿一覧が表示されないという事態が起こりました。
関係のあるコードはこちら
index.html.erb
<% require 'active_support/core_ext/numeric/conversions' %>
<h2>収入科目の新規データ登録</h2>
<p>登録年月を設定してください</p>
<%= form_tag({controller: :income_values, action: :new}, {method: :post}) do %>
<input type="month" name="year_month">
<input type="submit">
<% end %>
<h2>収入科目 データ一覧 </h2>
<% if @income_value.present? %>
<table>
<tr>
<th>登録年月</th>
<th>名称</th>
<th>値</th>
<th>備考</th>
<th>操作</th>
</tr>
<% @income_values.each do |income_value| %>
<tr>
<td><%= income_value.year_month.strftime('%Y年%m月') %></td>
<td><%= @incomes.find(income_value.income_id).name %></td>
<td><%= income_value.value.to_s(:delimited) %> 円</td>
<td><%= income_value.description %></td>
<td><%= link_to "編集", [:edit, income_value] %> | <%= link_to "削除", income_value, method: :delete, data: { confirm: "本当に削除しますか?"} %></td>
</tr>
<% end %>
</table>
<% else %>
<p>登録されているデータがありません。</p>
<% end %>
income_values_controller.rb
class IncomeValuesController < ApplicationController
def index
@incomes = Income.order(created_at: :asc)
@income_values = IncomeValue.order("year_month asc")
end
def show
@income_value = IncomeValue.find(params[:id])
end
def new
year_month_day = params[:year_month] + "-01"
@year_month = year_month_day.to_date
@incomes = Income.order(created_at: :asc)
@form = Form::IncomeForm.new
end
def edit
@income_value = IncomeValue.find(params[:id])
@income = Income.find(@income_value.income_id)
end
def create
@form = Form::IncomeForm.new(income_form_params)
if @form.save
redirect_to :income_values, notice: "登録しました"
else
redirect_to :income_values, notice: "登録に失敗しました"
end
end
def income_form_params
params
.require(:form_income_form)
.permit(income_values_attributes: Form::IncomeValue::REGISTRABLE_ATTRIBUTES)
end
def update
@income_value = IncomeValue.find(params[:id])
@income_value.assign_attributes(params[:income_value])
if @income_value.save
redirect_to :income_values, notice: "情報を更新しました"
else
一覧が表示されなかった原因は、
index.html.erb
の
<% if @income_value.present? %>
の変数が単数形だったからでした。
<% if @income_values.present? %>
として、解決!
しっかり確認することの大切さを改めて実感しました。
原因が分かって、
「一覧が表示される!」と思いきや、
「ActiveRecord::StatementInvalid」というエラーがでてしまったのです。。。
そして僕はこのエラーにとてつもなく苦しみました。
その2に続く👇
https://qiita.com/Shota_U/items/c93eb669b3f8078785eb