31:Postを押した時の保存処理の開発
rails routes #保存する際に必要な情報を見る POST /questions/:question_id/answers(.:format) answers#create
app/controllers/answers_controller.rb
×だめな例
class AnswersController < ApplicationController
def create
@question = Question.find(params[:question_id])
@answer = Answer.new
if @answer.save
redirect_to root_path, notice: 'Success!'
else
flash[:alert] = 'Save error!'
render :show
end
end
def edit
end
end
viewに値を渡す必要がある変数の場合は、@を付ける。
逆に、viewに値を渡す必要がある変数の場合は@を付けない(付けても動作する)。
状況に応じて、使い分けをしているため、
やりたい処理によって付けたり付けなかったりする。
◯良い例
class AnswersController < ApplicationController
def create
@question = Question.find(params[:question_id])
@answer = Answer.new
if @answer.update(answer_params)
redirect_to question_path(@question), notice: 'Success!'
else
redirect_to question_path(@question), notice: 'Invalid!'
end
end
def edit
end
private
def answer_params
params.require(:answer).permit(:content, :name, :question_id)
end
end
ストロングパラメーター↑を作成しています。
32:Answerモデルのバリデーション
フォームに空で保存するのを禁止します。
app/models/answer.rbに記述↓
class Answer < ApplicationRecord
belongs_to :question
validates :content, presence: true
validates :name, presence: true
end
33:回答一覧表示
app/views/answers/show.html.erbで記述を追加します。
<hr>
<div>
<h3>Answers</h3>
<table class="table table-striped">
<% if @question.answers.any? %>
<thead class="thead-light">
<tr>
<td>Answer</td>
<td>Name</td>
<td>Menu</td>
</tr>
</thead>
<tbody>
<% @question.answers.each do |answer| %>
<tr>
<td><%= answer.content %></td>
<td><%= answer.name %></td>
<td>[edit] [Delete]</td>
</tr>
<% end %>
</tbody>
<% else %>
<p>No answer yet.</p>
<% end %>
</table>
</div>
@question = Question.find #Quesutionsテーブルからfindしかしていないが class Question < ApplicationRecord has_many :answers
回答一覧が表示されたらOKです。

