Fin*_*nnn 36 ruby-on-rails ruby-on-rails-3
我想在保存模型后重定向到模型索引视图.
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
Run Code Online (Sandbox Code Playgroud)
我试过了
format.html { render action: "index", notice: 'Test was successfully created.' }
Run Code Online (Sandbox Code Playgroud)
但是我在/app/views/tests/index.html.erb中收到以下错误 -
undefined method `each' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)
知道出了什么问题吗?
Abi*_*bid 70
render action: "index"
Run Code Online (Sandbox Code Playgroud)
不会重定向,重定向和渲染不同的渲染,只会使用当前可用的变量渲染视图.使用重定向时,控制器的索引函数将运行,然后将从那里呈现视图.
你得到错误,因为你的索引视图期望你没有给它一些数组,因为你只是渲染"索引"而你没有视图需要的变量.
你可以用两种方式做到这一点
1-使用 render action: "index"
在呈现之前使视图可以使用它所需的所有变量,例如,它可能需要一个@posts变量,它用于显示帖子列表,因此您需要在渲染之前获取创建操作中的帖子
@posts = Post.find(:all)
Run Code Online (Sandbox Code Playgroud)
2-不要渲染做 redirect_to
您可以重定向到索引操作而不是呈现"索引",而索引操作将负责执行索引视图所需的必要操作
redirect_to action: "index"
Run Code Online (Sandbox Code Playgroud)
视图"index"包括"@ tests.each do"-loop.而方法create不提供变量"@tests".所以你有错误.你可以试试这个:
format.html { redirect_to action: "index", notice: 'Test was successfully created.' }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
43553 次 |
最近记录: |