Unknown19 Unknown19 - 7 months ago 34
Ruby Question

Rails - why I'm getting undefined method `name' for nil:NilClass

I'm displaying question by categories and each question has its own number. I made it like this(index.html.erb):

<% @categories.each do |category| %>
<div id=<%= "box#{category.id}" -%>>
<h1><%= category.name %></h1>
<% category.questions.each_with_index do |question, i| %>
<ul class="question-list" style="display: inline;">
<li><%= link_to (i + 1), show_path %></li>
</ul>
<% end %>
</div>
<% end %>


And when I click on question number I would like to show it like this(show.html.erb):

<div class="question-wrapper">
<h1><%= @category.name %></h1>
<div class="image left-align">
<%= question_image_tag(question, :large) %>
</div>
<div class="question-text right-align">
<%= @question.question_name %>
</div>
<p><%= @question.answer %></p>
</div>


This is my controller:

def index
@categories = Category.all
@questions = Question.all
end

def show
@categories = Category.all
@questions = Question.all
end


Now, I'm getting undefined method `name' for nil:NilClass (also throws error for all methods in show.html.erb) and I can't resolve it.

Question: What should I do to resolve undefined method `name' for nil:NilClass?

Update:
- stack trace


NoMethodError - undefined method
category' for nil:NilClass:
app/controllers/quizz_controller.rb:13:in
show'


routes.rb

Rails.application.routes.draw do
mount Attachinary::Engine => "/attachinary"
root to: "quizz#home"
%w(quizz
show).each do |page|
get page, to: "quizz##{page}", as: page
end
resources :categories
resources questions
end

dkp dkp
Answer

You just need to pass the question id with the params and find the @question from the question id in show action of your controller.

Your respective views and controller code should look as follows:

index.html.erb

<% @categories.each do |category| %>
 <div id=<%= "box#{category.id}" -%>>
    <h1><%= category.name %></h1>
    <% category.questions.each_with_index do |question, i| %>
        <ul class="question-list" style="display: inline;">
            <li><%= link_to (i + 1), show_path(question_id: question.id) %></li>
        </ul>
    <% end %>
 </div>

Controller

def show
  @question = Question.find_by_id(params[:question_id])
  @category = @question.category
end

show.html.erb

<div class="question-wrapper">
   <h1><%= @category.name %></h1>
   <div class="image left-align">
     <%= question_image_tag(question, :large) %>
   </div>
   <div class="question-text right-align">
    <%= @question.question_name %>
   </div>
   <p><%= @question.answer %></p>
</div>