Louis93
Louis93

Reputation: 3913

Why is my instance variable holding `nil` when I render this view?

When I view my index view directly, it behaves as expected.

However, when I try and render the index view right after creating a record, my variables become nil, and I see this message:

enter image description here Any insight into why this could be happening would b

Here's my 'TodoController`:

class TodosController < ApplicationController
    def index
        @todo = Todo.new
        @todos = Todo.where(done:false,user:current_user.email)
        @todones = Todo.where(done:true,user:current_user.email)
    end

 def create
     @todo = Todo.new(todo_params)
     respond_to do |format|
         if @todo.save
             format.js
             format.html {render "index"} #WHERE I RENDER INDEX PROMPTING THE ERROR!
         else
             render "new"
         end
     end
 end
 end

And in my index.html.erb view, I have this:

<h3> TO DO </h3>
<ul class="todos">
        <% @todos.each do |t| %>
            <%= render partial: "todo", object:t  %>
        <% end %>
</ul>

The partial _todo.html.erb:

<li>
    <strong><%= todo.name %></strong>
    <small><%= link_to "Mark as done", todo_path(todo.id), :method => :put %></small>
</li>

Now when I try to insert a

Upvotes: 0

Views: 641

Answers (1)

jmromer
jmromer

Reputation: 2236

@todos is nil, since it's being created in the view rather than being populated in the create action from the controller.

A quick fix is to add a condition to your view:

<% unless @todos.nil? %>
  <ul class="todos">
        <% @todos.each do |t| %>
            <%= render partial: "todo", object:t  %>
        <% end %>
  </ul>
<% end %>

Alternatively, you can populate @todos in create, but I doubt that's the intent.

If you want to send the user to the index page after a create action, I'd recommend doing so through a new HTTP request by using redirect_to index_url instead of rendering the index view from the create action.

That should obviate the need for a '<% unless @todos.nil? %>` statement in your view.

Upvotes: 2

Related Questions