redirect to index rather than show after save

ruby-on-rails, ruby-on-rails-3

Solution

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"

Problem

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?

Original source

Related problems