I am creating a question posting/answering application that utilizes CRUD processing in Ruby on Rails.
When posting the answer to the question, it is assumed that it will be rendered if a validation error occurs.
At that time, I tried to define the initial value of the instance variable, but the following error occurred.

ActiveRecord :: RecordNotFound in AnswersController # create
Couldn't find Question without an ID
Corresponding source code
class AnswersController</pre>
class QuestionsController</pre>
<p>[Question]<br><% = markdown (@ question.title)%></p>
<p>[Details]<br><% = markdown (@ question.detail)%></p>
<% @ answers.each do | a |%>
  <% = markdown (a.content)%>
<% end%>
 Post answer 
<% = form_with model: [@question, @answer], local: true do | form |%>
<% = form.label: title, "[Answer]"%>
<% = form.text_area: content, class: "form-control"%>
  <% = form.submit "submit", class: "btn btn-primary btn-block"%>
<% end%>
<% end%>
Rails.application.routes.draw do
  devise_for: admin_users, ActiveAdmin :: Devise.config
  ActiveAdmin.routes (self)
  devise_for: users
  root "movies # index"
  resources: movies
  resources: aws_texts, only: [: index ,: show]
  resources: questions do
    resource: answers, only: [: create,: edit,: update,: destroy]
What I tried

Similar to the show method of questions_controller.rb, to the part to be rendered by the create method of answers_controller.rb

@question = Question.all
 @question = Question.find (params [: id])
 @answers = @ question.answers
 flash.now [: alert] = "Failed to post answer"
 render "questions/show"

I tried to define an instance variable like this.

Supplementary information (FW/tool version, etc.)

ruby 2.6.6

  • Answer # 1

    @question = Question.find (params [: question_id]

  • Answer # 2

    The error message is as follows. Since id is not specified when creating a new one (id is assigned when it is saved in the database),params [: id]Nothing passes to.

    @question = Question.newI think it is appropriate to create an empty one with (in the previous line)@question = Question.allIs completely meaningless as it will be overwritten on the next line).