4

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}) %>

@usersインスタンス変数をに置き換えても、User.allリダイレクト後にエラーは発生しません。

@usersリダイレクト後は空なので、エラーだと思います。しかし、なぜ?@usersnewおよびeditコントローラーで定義されます。

私のコントローラーは:

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 に答える