Alex Rivera | Logout

redirect to index rather than show after save

Asked 2012-05-03T21:42:56.073
44

I want to redirect to the a models index view after saving my model.

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

I've tried

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

but I get the following error in /app/views/tests/index.html.erb -

   undefined method `each' for nil:NilClass

Any idea what's going wrong?

Edit
Report

2 Answers

7

The view "index" includes "@tests.each do"-loop. And method create does not provide the variable "@tests". so you have the error. You can try this:

format.html { redirect_to action: "index", notice: 'Test was successfully created.' }
answered 2012-05-03T21:53:10.657
4

Its very simple.

Just rewrite your method like

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

It will redirect to the index page

answered 2013-02-08T06:21:51.800

Your Answer