Rails 关于 redirect_to 重定向的同时传参数

526699159 · April 03, 2012 · Last by darren replied at October 15, 2019 · 21914 hits

书中云:当控制器中的 action 不是将模型返回的数据提交给某个视图显示,而是需要把处理结果交给另一个 action 时,我们可以使用 Rails 的重定向功能。 然后我作了个实验

class RedirectController < ApplicationController
  def index
      @student=Student.find(29)
      redirect_to :action=>"another",:notice=>'student can be here'
  end
  def another

  end

end


我要把从 model 取得的 student 信息在 another.html.erb 中显示

<%= notice%>
<%=@student.name%>


但是我在 another.html.erb 中什么都接收不到啊,rails 也没把处理结果@studen传给另一个 action(another) 啊 这是怎么回事呢

@student 只存在于 index 这个方法里 和 它所渲染 (render) 的资源例如 index.html.erb里。
redirect_to 是跳转到另一个地方。你都已经跳转到 another 这个 action 里了。@student 怎么还会存在呢... 回去补补文档..

首先要理解redirect_to到底作了什么?

redirect_to 是给浏览器发送一个 304 的响应,告诉浏览器去请求另外一个 url,当浏览器根据这个 url 发起请求达到服务器端后,用来响应请求的 controller 已经不是你之前的那个 controller 实例了,所以当然没有@student这个实例了。

如果你想要在 another 里面也取得 @student 那么你需要在 redirect 的时候附带上id参数,好让浏览器向 another action 发起带 id 参数的请求,然后 another 在依然从 params[:id] 取得 id 然后从数据库中取出 student。

@lgn21st 那岂不是传过去个 id 到那边再取了一遍 也不是传过去的啊 书上骗我呀=。=

#3 楼 @526699159 我更原意相信是你对书上的理解有误。是哪本书?原文是怎么说的?

@lgn21st Ruby on Rails Web 开发学习实录 第 401 页原文 就是我发的第一句哦 一个字不差 伤心了=.=

@526699159 希望对你有用 Sets a flash that will not be available to the next action, only to the current.

flash.now[:message] = "Hello current action" This method enables you to use the flash as a central messaging system in your app. When you need to pass an object to the next action, you use the standard flash assign ([]=). When you need to pass an object to the current action, you use now, and your object will vanish when the current action is done.

Entries set via now are accessed the same way as standard entries: flash['my-key'].

Keeps either the entire current flash or a specific flash entry available for the next action:

flash.keep # keeps the entire flash flash.keep(:notice) # keeps only the "notice" entry, the rest of the flash is discarded

还有 这个是 重定向 方法的 doc http://api.rubyonrails.org/classes/ActionController/Redirecting.html#method-i-redirect_to 实例变量 是过不去了 但是 可以 把你打算传递的实例变量 的 id 或者 类似 param 作为 重定向 URL

书写得一点没错,例子写得有错了。 当然你硬把@student理解成返回结果,而不理解成模型返回的数据,那也冒得办法。

redirect_to 的时候一般用 session 来保存数据。。

@526699159 redirect_to 当然可以携带参数。redirect_to 是常见的转向功能,可以转向到第三方应用,也可以转向到自己的 action。转向的时候,只需要构造出来 http://url?paramet1=hello这样的结构即可。 你所举的例子的做法: 1、获取 another 这个 action 的 path 方法,或者 url 方法。你可以通过 rake routes 获取,假设是 new_another_path 2, redirect_to new_another_path(param1: param1_value) that is ok.

嗯,按照 9 楼的方法可以传值过去

不用 redirect_to ,直接调用 another 方法

You need to Sign in before reply, if you don't have an account, please Sign up first.