What is causing NoMethodError in my CRUD?

55 Views Asked by At

I am student working on my first project on my own. The user is supposed to be able to create a to-do list. I have my form partial displayed and am trying to now render the list items through a partial. After altering my routes.rb and items_controller.rb I still receive NoMethodError.

Here is the stack trace.

Completed 500 Internal Server Error in 23ms (ActiveRecord: 0.2ms)

ActionView::Template::Error (undefined local variable or method `items' for #<#<Class:0x007fa1c3b4e238>:0x007fa1bd6f2258>):
    1: <% items.each do |i| %>
    2:   <%= i.name %>
    3: <% end %>
  app/views/items/_item.html.erb:1:in `_app_views_items__item_html_erb___4201771908086516106_70166314068980'
  app/views/users/show.html.erb:5:in `_app_views_users_show_html_erb__1693372631105662933_70166313045680'

items_controller.rb

class ItemsController < ApplicationController
  def index
    @items = Item.all
  end

  def show
    @item = Item.find(params[:id])
  end

  def new
    @item = Item.new
  end

  def edit
    @item = Item.find(params[:id])
  end

  def create
    @item = Item.new(params.require(:item).permit(:name))

    if @item.save
      flash[:notice] = "The item was added to your list."
      redirect_to :show
    else
      flash[:error] = "There was a problem creating your item."
      redirect_to :new
    end
  end
end

routes.rb

Rails.application.routes.draw do

  get 'welcome/index'
  get 'welcome/about'

  # resources :welcome, only: [] do
  #   collection do
  #     get 'about'
  #     get 'index'
  #   end
  # end

  devise_for :users

  resources :users, only: [:show] 
  resources :items

  root to: 'welcome#index'
end

users/show.html.erb

<h1>Welcome <%= current_user.name %></h1>
<p>Add an item</p>

<%= render partial: 'items/form', locals: { item: @new_item } %>
<%= render partial: 'items/item', locals: { item: @items } %>

items/_item.html.erb

<% items.each do |i| %>
  <%= i.name %>
<% end %>

EDIT: Here is my users_controller.rb

class UsersController < ApplicationController
  before_action :authenticate_user!

  def show
    @user = User.find(params[:id])
    @new_item = Item.new
  end
end
1

There are 1 best solutions below

6
On BEST ANSWER

You need to use local variable item, which you passed to the partial _item.html.erb. :

<% item.each do |i| %>
  <%= i.name %>
<% end %>

and ...

class UsersController < ApplicationController
  before_action :authenticate_user!

  def show
    @user = User.find(params[:id])
    @new_item = Item.new
    @items = Item.all
  end
end