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?
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"
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.' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With