我正在学习自己的第一个项目。用户应该能够创建待办事项列表。我的表单部分显示,我现在尝试通过部分呈现列表项。在改变我的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
用户/ 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 } %>
项/ _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
答案 0 :(得分:0)
您需要使用传递给部分 item
的本地变量_item.html.erb
。 :
<% 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