Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect to index rather than show after save

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?

like image 995
Finnnn Avatar asked May 03 '12 21:05

Finnnn


2 Answers

render action: "index"

will not redirect, redirecting and rendering a different, render will just render the view with the current available variables for it. while with a redirect the index function of the controller will run and then the view will be rendered from there.

you are getting the error because your index view is expecting some array which you are not giving to it since you are just rendering "index" and you dont have the variables that the view needs.

You can do it in 2 ways

1- using render action: "index"

make available to the view all the variables that it needs before you render, for example it may be needing a @posts variable which it uses to show list of posts so you need to get the posts in your create action before you render

@posts = Post.find(:all)

2- don't render do a redirect_to

instead of rendering "index" you redirect to the index action which will take care of doing the necessary things that the index view needs

redirect_to action: "index"
like image 53
Abid Avatar answered Nov 15 '22 14:11

Abid


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.' }
like image 7
okodo Avatar answered Nov 15 '22 12:11

okodo