是什么导致我的 CRUD 出现 NoMethodError?

What is causing NoMethodError in my CRUD?

我是一名学生,正在独立完成我的第一个项目。用户应该能够创建待办事项列表。我已部分显示我的表单,现在正尝试通过部分呈现列表项。更改我的 routes.rb 和 items_controller.rb 后,我仍然收到 NoMethodError。

这是堆栈跟踪。

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 %>

编辑:这是我的 users_controller.rb

class UsersController < ApplicationController
  before_action :authenticate_user!

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

您需要使用您传递给 partial _item.html.erb 的局部变量 item。 :

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

和...

class UsersController < ApplicationController
  before_action :authenticate_user!

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