4

In a Rails 3.2 app, when a certain form fails to save (validation fails) and redirects back to the form I get an error:

undefined method `map' for nil:NilClass

This form does not display any errors when navigating directly to the new or edit paths.

The error is coming from a select field with a custom options_from_collection_for_select method.

<%= f.select(:user_ids, options_from_collection_for_select_with_attributes(@users, :id, :name, 'data-attributes', :attributes ), {include_blank:true}, {multiple:true}) %>

If I replace the instance variable @users with User.all then I don't get an error after redirect.

I guess @users is empty after the redirect, hence the error. But why? @users is defined in the new and edit controllers.

My controller is:

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
4

1 回答 1

16

这是因为如果失败,您实际上并没有执行“新”操作。这是一个典型的控制器结构

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
于 2012-06-10T18:04:03.143 回答