【发布时间】:2016-04-22 04:16:05
【问题描述】:
尝试使用 form_for,我收到错误“表单中的第一个参数不能包含 nil 或为空”。错误在第一行突出显示:
<%= form_for @item do |f| %> #------error highlited here
<%= f.label :Task %>
<%= f.text_field :name, placeholder: "What do you have to do?" %>
<% end %>
部分的:
<%= form_for @item do |f| %>
<%= f.label :Task %>
<%= f.text_field :name, placeholder: "What do you have to do?" %>
<% end %>
控制器:
```
class ItemsController < ApplicationController
def index
@items = Item.all
end
def new
@item = Item.new
end
def create
@item = Item.new
@item.name = params[:item][:name]
@item.user = current_user
if @item.save
flash[:notice] = "Item added; go accomplish it!"
else
flash.now[:alert] = "Uh oh, it didn't save. Try again."
render :new
end
end
def show
@item = Item.find(params[:id])
end
end
```
而且,显示视图(我称之为部分):
<%= render partial: 'items/form', item: Item.new, locals: {items: @item} %>
到目前为止,我的研究表明问题可能出在这些文件中。我已经看到我可以简单地写,,但我想避免这种情况,因为所有人都反对它。这个错误是如何解决的?如何确保第一个参数不为空/nil?(我确实在 Rails 控制台中创建了一个项目)
【问题讨论】: