gpt4 book ai didi

ruby-on-rails - 验证失败并且表单重定向回自身后,为什么实例变量为空?

转载 作者:行者123 更新时间:2023-12-01 22:58:30 26 4
gpt4 key购买 nike

在 Rails 3.2 应用程序中,当某个表单无法保存(验证失败)并重定向回表单时,我收到错误消息:

undefined method `map' for nil:NilClass

直接导航到新路径或编辑路径时,此表单不会显示任何错误。

错误来自带有自定义 options_from_collection_for_select 的选择字段方法。
<%= f.select(:user_ids, options_from_collection_for_select_with_attributes(@users, :id, :name, 'data-attributes', :attributes ), {include_blank:true}, {multiple:true}) %>

如果我替换实例变量 @usersUser.all那么重定向后我就不会收到错误消息。

我猜 @users重定向后为空,因此出现错误。但为什么? @users在 new 和 edit Controller 中定义。

我的 Controller 是:
def create
--bunch of stuff
if @model.save
--bunch of stuff
respond_to do |format|
format.html { render :text => model_url(@model) }
format.html { redirect_to(@model, :notice => 'Success!.') }
format.xml { render :xml => @model, :status => :created, :location => @model }
end

else
respond_to do |format|
format.html { render :action => "new" }
format.xml { render :xml => @model.errors, :status => :unprocessable_entity }
end
end
end

最佳答案

这是因为如果失败,您实际上不会执行"new"操作。这是一个典型的 Controller 结构

class PotsController < ApplicationController

def new
@pot = Pot.new
@users = User.all
end

def create
@pot = Pot.new(params[:pot])
if @pot.create
redirect_to @pot, notice: "Created"
else
#****you are here****
render :new
end
end
end

在上面,如果 pot.create失败,它只是呈现新模板。在这种情况下,您应该做的是获取实例变量
  def create
@pot = Pot.new(params[:pot])
if @pot.create
redirect_to @pot, notice: "Created"
else
@users = User.all #this is the important line
render :new
end
end

关于ruby-on-rails - 验证失败并且表单重定向回自身后,为什么实例变量为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10970868/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com