【问题标题】:redirect to index rather than show after save保存后重定向到索引而不是显示
【发布时间】:2012-05-03 21:42:56
【问题描述】:

我想在保存模型后重定向到模型索引视图。

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

我试过了

    format.html { render action: "index", notice: 'Test was successfully created.' }

但我在 /app/views/tests/index.html.erb 中收到以下错误 -

   undefined method `each' for nil:NilClass

知道出了什么问题吗?

【问题讨论】:

  • 对“每个”的调用在哪里?
  • 已编辑问题 - 在索引视图中。

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:
render action: "index"

不会重定向、重定向和渲染不同的,render 只会渲染具有当前可用变量的视图。而使用重定向,控制器的索引功能将运行,然后视图将从那里呈现。

您收到错误是因为您的索引视图需要一些您没有提供给它的数组,因为您只是呈现“索引”并且您没有视图需要的变量。

你可以通过两种方式做到这一点

1- 使用render action: "index"

在渲染之前为视图提供它需要的所有变量,例如,它可能需要一个 @posts 变量,用于显示帖子列表,因此您需要在渲染之前在创建操作中获取帖子

@posts = Post.find(:all)

2- 不要渲染做一个redirect_to

您重定向到索引操作而不是呈现“索引”,该操作将负责执行索引视图所需的必要操作

redirect_to action: "index"

【讨论】:

  • 谢谢,这有效,但我的通知没有显示。我可以看到它作为 url 参数 /tests?notice=Test+was+successfully+created 传递。
  • 您是在布局中呈现通知还是在某处呈现视图?
  • 是的,我的观点中有

    。感谢您查看此内容。
  • 改成<p id="notice"><%= flash[:notice] %></p>
  • 它有点长,但您可能应该使用其中一种 *_url(例如redirect_to posts_url)方法。这解决了我的通知出现的问题。
【解决方案2】:

视图“索引”包括“@tests.each do”-loop。并且方法 create 不提供变量“@tests”。所以你有错误。 你可以试试这个:

format.html { redirect_to action: "index", notice: 'Test was successfully created.' }

【讨论】:

  • 这可行,但我的通知没有显示。我可以看到它作为 url 参数 /tests?notice=Test+was+successfully+created 传递。
  • 试试这个:format.html { flash[:notice] = '测试已成功创建。'和 redirect_to 操作:“索引”}
  • @user1297959 您能否更新您的答案以包含您的评论?没有其他答案,它非常有用。
【解决方案3】:

它非常简单。

只需像这样重写你的方法

def create
  @test = Test.new(params[:test])

  respond_to do |format|
    if @test.save
      format.html { **redirect_to tests_path**, notice: 'test was successfully created.' }
    else
      format.html { render action: "new" }
    end
  end
end

它将重定向到索引页面

【讨论】:

  • 用**括起来的项目是需要从默认重定向更改的内容。
【解决方案4】:

有两种方法:

  1. 使用来自rake routes的资源:

format.html { redirect_to todo_items_url, notice: 'Todo item was successfully created.' }

  1. 使用控制器动作:

format.html { redirect_to action: :index, notice: 'Todo item was successfully created.' }

【讨论】:

  • 明白了吗? OSX 10.12 上的 Rails 4,只有第一种方法支持 flash :notice item :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-16
  • 2014-04-16
  • 2013-06-26
  • 2017-07-05
  • 1970-01-01
  • 2015-11-11
  • 1970-01-01
相关资源
最近更新 更多