保存后重定向到索引而不是显示

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)

  • 谢谢,可以,但是没有显示我的通知。我可以看到它作为url参数/ tests?notice = Test + was + successful + created通过了。 (2认同)
  • 它更长一些,但是您可能应该使用* _url(例如`redirect_to posts_url`)方法之一。我的通知出现的此已解决的问题。 (2认同)

oko*_*odo 7

视图"index"包括"@ tests.each do"-loop.而方法create不提供变量"@tests".所以你有错误.你可以试试这个:

format.html { redirect_to action: "index", notice: 'Test was successfully created.' }
Run Code Online (Sandbox Code Playgroud)

  • 试试这个:format.html {flash [:notice] ='测试已成功创建.' 和redirect_to动作:"index"} (4认同)
  • 这有效,但我的通知没有显示.我可以看到它是作为url param/tests传递的吗?notice = Test +是+成功+创建的. (2认同)