Ruby on rails 编辑操作错误(表单中的第一个参数不能包含nil)
在这个Rails应用程序中,用户可以编写故事并将其添加到集合中。在编写故事时,用户可以在stories/new.html.erb视图中通过模式将其添加到现有集合或创建新集合 我有这个新的行动工作,但编辑行动是坏的。它抛出一个错误,表示 表单中的第一个参数在此行不能包含nil或为空Ruby on rails 编辑操作错误(表单中的第一个参数不能包含nil),ruby-on-rails,Ruby On Rails,在这个Rails应用程序中,用户可以编写故事并将其添加到集合中。在编写故事时,用户可以在stories/new.html.erb视图中通过模式将其添加到现有集合或创建新集合 我有这个新的行动工作,但编辑行动是坏的。它抛出一个错误,表示 表单中的第一个参数在此行不能包含nil或为空 <%= form_for [@user, @collection] do |f| %> stories/edit.html.erb加载_form.html.erb部分 <div class="
<%= form_for [@user, @collection] do |f| %>
stories/edit.html.erb加载_form.html.erb部分
<div class="modal-body">
<%= form_for [@user, @collection] do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_area :description, class: "form-control collection-desc-input-box", placeholder: "Give it a description (this is optional)" %>
</div>
<div class="form-group">
<%= f.submit class: "btn btn-lakeside" %>
</div>
<% end %>
</div>
编辑:
通过将Collection.new放入编辑操作中修复了该问题。如果有人能解释发生了什么就好了。我通过反复试验解决了这个问题。谢谢
def edit
@story = Story.friendly.find(params[:id])
@user = current_user
@collection = Collection.new
end
在编辑操作中初始化/设置
@user
和@collection
,它们为零,因此会出现错误。因为它们是为new
操作初始化的,所以它正在工作
对于@user
和@collection
,您可以执行如下操作,并可以在各自的操作中进行相应的初始化:
before_action :set_user, only: [:new, :edit]
private
def set_user
@user = current_user
end
存储控制器中缺少了
@user
和@collection
实例变量
请尝试以下代码:
#stories_controller.rb
def new
@story = Story.new
authorize @story
@user = current_user
@collection = Collection.new
end
def edit
@story = Story.friendly.find(params[:id])
@user = User.find(params[:id])
@collection = Collection.find(params[:collection_id])
end
仍然得到相同的错误。在其他操作和视图中,我可以调用当前用户,但在这里它拒绝工作。您登录了吗?我怀疑,如果您使用的是Deviate,那么请将
放在\u action:authenticate\u user
之前,以验证用户登录。大多数情况下,用户已注销。已设法解决该问题,但我不知道我是如何解决的。解决方案在上面的编辑中。如果你能帮我理解发生了什么,那就太好了,谢谢!!这就是我要求你做的,初始化@user和@collection
,这就是你做的。在你的控制台中,你可以检查这个,当你键入user
或任何像asdfgh
这样的随机字符串时,它会抛出未初始化变量或方法的错误,但当您将其设置为实例变量,如@user
或@asdfgh
时,它将返回nil,并且不会引发异常。因此,当您将@user
和@collection
传递给表单时,由于未初始化,它们的值为nil
,表单不接受nil值。由于您在控制器中设置了它们,它正在工作并设法解决问题,但我不知道我是如何做到的。解决方案在上面的编辑中。如果你能帮我理解发生了什么,那就太好了,谢谢!!
before_action :set_user, only: [:new, :edit]
private
def set_user
@user = current_user
end
#stories_controller.rb
def new
@story = Story.new
authorize @story
@user = current_user
@collection = Collection.new
end
def edit
@story = Story.friendly.find(params[:id])
@user = User.find(params[:id])
@collection = Collection.find(params[:collection_id])
end