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:
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
@todosisnil, since it's being created in the view rather than being populated in thecreateaction from the controller.A quick fix is to add a condition to your view:
Alternatively, you can populate
@todosincreate, but I doubt that's the intent.If you want to send the user to the index page after a
createaction, I'd recommend doing so through a new HTTP request by usingredirect_to index_urlinstead of rendering the index view from thecreateaction.That should obviate the need for a '<% unless @todos.nil? %>` statement in your view.