dimanche 15 mars 2015

Undefined method in User_Controller - To do List

I'm working on a to-do list in rails and I'm getting the following: undefined method `items' for nil:NilClass in my users_controller.rb.


The program was working to the point where I could delete and create the list and have it take me to the new_list_path. However, after I came back a day later, I got the undefined method.


Currently, the user is logged in and there is no list. I tried to add a list via rails console but that didn't work.


users_controller.rb



class UsersController < ApplicationController

def show
return redirect_to new_list_path unless current_user
@list = current_user.list
@items = @list.items
end
end


I am directing everything to go the View/Users/Show page with some partials:


users/show.html.erb



<h1><%= @list.title %></h1>
<%= link_to "Delete List", @list, method: :delete %>
<h2 class="media-heading"><%= current_user.name %></h2>
<%= render partial: 'items/form'%>
<%= render partial: 'items/item', collection: @items %>


Partials are here

items/_form.html.erb



<%= form_for [@list, @list.items.new] do |f| %>
<div class="form-group">
<h4>Add an Item:</h4><br/>
</div>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control', placeholder: "Add an Item:" %>
</div>
<div class= "form-group">
<%= f.submit "Create Item", class: 'btn btn-success' %>
</div>
<% end %>


items/_item.html.erb



<small class="media-heading">
<p><%= item.name %></p>
<%# time_ago_in_words(item.created_at) %>
</small>


Here are my other two controllers:


lists_controller.rb



class ListsController < ApplicationController
before_action :authenticate_user!

def new
@list = List.new
end

def create
@list = List.new(list_params)
@list.user = current_user

if @list.save
flash[:notice] = "List was saved."
redirect_to current_user
else
flash[:error] = "There was a problem saving your list."
redirect_to user_path(current_user)
end
end

def destroy
@list = List.find(params[:id])
if @list.destroy
redirect_to new_list_path
else
redirect_to current_user
end
end

def edit
end

private
def list_params
params.require(:list).permit(:title)
end
end


items_controller.rb



class ItemsController < ApplicationController

def show
@items = Item.all
end

def create
@list = List.find(params[:list_id])
@item = Item.new(item_params)
@item.list = @list # after initializiation, before saving
if @item.save
flash[:notice] = "Item was saved."
redirect_to current_user
else
flash[:error] = "There was a problem saving your item."
redirect_to current_user
end
end

private
def item_params
params.require(:item).permit(:name)
end
end


I'm wondering how it's broken when it worked previously.


Aucun commentaire:

Enregistrer un commentaire