43

モデルを保存した後、モデルのインデックスビューにリダイレクトしたい。

def create
  @test = Test.new(params[:test])

  respond_to do |format|
    if @test.save
      format.html { redirect_to @test, notice: 'test was successfully created.' }
    else
      format.html { render action: "new" }
    end
  end
end

私はもう試した

    format.html { render action: "index", notice: 'Test was successfully created.' }

しかし、/ app / views / tests/index.html.erbで次のエラーが発生します-

   undefined method `each' for nil:NilClass

何が悪いのか分かりますか?

4

4 に答える 4

80
render action: "index"

リダイレクト、リダイレクト、および別のレンダリングは行いません。renderは、現在使用可能な変数を使用してビューをレンダリングするだけです。リダイレクトを使用すると、コントローラーのインデックス機能が実行され、そこからビューがレンダリングされます。

「インデックス」をレンダリングしているだけで、ビューに必要な変数がないため、インデックスビューが指定していない配列を予期しているため、エラーが発生します。

あなたは2つの方法でそれを行うことができます

1-使用render action: "index"

レンダリングする前に必要なすべての変数を表示できるようにします。たとえば、投稿のリストを表示するために使用する@posts変数が必要な場合があるため、レンダリングする前に作成アクションで投稿を取得する必要があります。

@posts = Post.find(:all)

2-レンダリングしないでくださいredirect_to

「インデックス」をレンダリングする代わりに、インデックスビューに必要な処理を実行するインデックスアクションにリダイレクトします

redirect_to action: "index"
于 2012-05-03T21:52:36.723 に答える
7

ビュー「index」には「@tests.eachdo」ループが含まれます。また、メソッドcreateは変数「@tests」を提供しません。だからあなたはエラーがあります。あなたはこれを試すことができます:

format.html { redirect_to action: "index", notice: 'Test was successfully created.' }
于 2012-05-03T21:53:10.657 に答える
3

その非常に簡単です。

メソッドを次のように書き直してください

def create
  @test = Test.new(params[:test])

  respond_to do |format|
    if @test.save
      format.html { **redirect_to tests_path**, notice: 'test was successfully created.' }
    else
      format.html { render action: "new" }
    end
  end
end

インデックスページにリダイレクトされます

于 2013-02-08T06:21:51.800 に答える
3

これを行うには2つの方法があります。

  1. からのリソースを使用するrake routes

format.html { redirect_to todo_items_url, notice: 'Todo item was successfully created.' }

  1. コントローラアクションの使用:

format.html { redirect_to action: :index, notice: 'Todo item was successfully created.' }

于 2016-03-12T16:40:32.617 に答える