加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 01:49:51 所属栏目:百科 来源:网络整理
导读:在Rails 3.2应用程序中,当某个表单无法保存(验证失败)并重定向回到表单时,我收到一个错误: undefined method `map' for nil:NilClass 直接导航到新路径或编辑路径时,此表单不显示任何错误. 错误来自具有自定义options_from_collection_for_select方法的选择
在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}) %>

如果我用User.all替换实例变量@users,那么重定向后我不会收到错误.

我想@users在重定向后是空的,因此错误.但为什么? @users在新的和编辑控制器中定义.

我的控制器是:

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

解决方法

这是因为如果失败,你实际上并没有执行“新”动作.这是典型的控制器结构

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读