【本日の学習内容:共同開発(質問集ページに回答部分を実装)】
回答部分を実装について、あいまいだった点を整理しました。
ルーティングのネスト
answersのルーティングをquestionsにネストさせる意味についてですが
ネストさせることで以下のようなルーティングになるため、
question_answers GET /questions/:question_id/answers(.:format) answers#index
POST /questions/:question_id/answers(.:format) answers#create
new_question_answer GET /questions/:question_id/answers/new(.:format) answers#new
edit_question_answer GET /questions/:question_id/answers/:id/edit(.:format) answers#edit
question_answer GET /questions/:question_id/answers/:id(.:format) answers#show
PATCH /questions/:question_id/answers/:id(.:format) answers#update
PUT /questions/:question_id/answers/:id(.:format) answers#update
DELETE /questions/:question_id/answers/:id(.:format) answers#destroy
questionが持っているquestion_idに結びつくanswers情報をコントローラに送るためにネストしている。
form_withのmodelに2つのモデルを指定
<%= form_with model: [@question, @answer], local: true do |f| %>
ルーティングをネストして作ったパスへのURL(POSTの/questions/:question_id/answers(.:format) )を飛ばすために、以下のように記述をしているが、
model: [@親モデル, @子モデル]
この記述で、どうして飛ぶURLがPOSTの/questions/:question_id/answers(.:format) となるのかがわからなかったが、これはform_withの仕様なので追求しすぎても不毛に終わってしまう。
重要なのは,questionとanswerの2つの情報があれば
/questions/:question_id/answers(.:format)
のようなURLを自動生成できるということ。
またanswerの情報についてはAnswer.newを@answerに格納しているため、新規投稿のcreateアクションに流すように自動判定するのは自然なこと。