Lax_Sam
Lax_Sam

Reputation: 1139

Undefined method for '[]' for nil:NilClass in Rails

I am trying to validate answer for question model with options. I have a link_to check_answer method for every question. The problem is the question object is not passed to the method. On the same page I have link_to edit method where the question object is passed. Even the url on the link_to check_answer shows the correct url. Where is the mistake here?

show.html.erb

<p>
  <strong>Body:</strong>
  <%= @question.body %>
</p>

<p>
  <strong>Option:</strong>
  <% @question.options.each do |p| %>
    <%= radio_button_tag('option',p.id) %>
    <%= p.body %>

  <% end %>
</p>
<p><%= link_to 'Check Answer', check_answer_question_path(@question) %></p>
<p>
  <strong>User:</strong>
  <%= @question.user.email %>
</p>

<%= link_to 'Edit', edit_question_path(@question) %> |
<%= link_to 'Back', questions_path %>

Here the link_to Edit passes the @question object to the controller but not the link_to Check Answer.

controller.rb

def check_answer        
    puts(@question.id)        
end

private
    # Use callbacks to share common setup or constraints between actions.
    def set_question
      @question = Question.find(params[:id])
    end

routes.rb

Rails.application.routes.draw do
  resources :questions do
    member do
        get 'check_answer'
    end
  end
end

error stack

Started GET "/questions/22/check_answer" for 127.0.0.1 at 2019-05-04 19:51:17 +0530
Processing by QuestionsController#check_answer as HTML
  Parameters: {"id"=>"22"}
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ /home/laxmanrm/.rvm/gems/ruby-2.6.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
------------------------------------check_answer------------------------------------------
Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.4ms)



NoMethodError (undefined method `id' for nil:NilClass):

app/controllers/questions_controller.rb:72:in `check_answer'

error

enter image description here

Upvotes: 0

Views: 1195

Answers (1)

You need to populate your @question instance variable, before calling your check_answer action, for that you can use before_action

before_action :set_question, only: [:show, :edit, :update, :destroy, :check_answer]

Upvotes: 2

Related Questions