Home>

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
answers_controller.rb
class AnswersController</pre>
<pre><code>questions_controller.rb
class QuestionsController</pre>
<pre><code>show.html.erb
<p>[Question]<br><% = markdown (@ question.title)%></p>
<p>[Details]<br><% = markdown (@ question.detail)%></p>
 Answer 
<% @ answers.each do | a |%>
  
  <% = markdown (a.content)%>
  
<hr>
<% 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%>
-Omitted-
routes.rb
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]
  end
end
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.)

Rails 6.0.3.3
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).