在rails上的ruby中将一个变量从一个动作发送到另一个动作

时间:2015-10-12 09:56:21

标签: ruby-on-rails ruby

控制器中的代码是

if params["type"] == "user"
  respond_to do |format|
    format.html { redirect_to home_user_path, notice: "abc" }
  end

如果我发送通知变量然后工作正常,但我想用我自己的密钥发送,如

format.html { redirect_to home_user_path, search: "abc" }

它没有收到

2 个答案:

答案 0 :(得分:1)

这是Ruby的可选括号的一个问题:有时候很难看出哪个方法调用被视为参数。

请改为尝试:

format.html { redirect_to home_user_path(search: "abc") }

这将重定向到home_user_path并将params[:search]设置为“abc”。

答案 1 :(得分:1)

你必须记住你不是"发送"变量到另一个动作;您正在调用其他操作,并使用变量(数据)填充它:

<强> 1。实例变量

您可以设置一个实例变量,然后在下一个操作中可用:

 def your_action
   @search = "abc"
   respond_to do |format|
     format.html { redirect_to home_user_path } #-> @search will be available in the other view
   end
 end

<强> 2。会话

您目前正在尝试使用sessions填充数据:

def your_action
   redirect_to home_user_path, search: "abc"
end

#app/views/controller/your_action.html.erb
<%= flash[:search] %>

第3。网址

最后,您可以通过路线设置网址中的值:

def your_action
   redirect_to home_user_path(search: "abc") #-> you'll probably need to set the user object too, judging from the route name
end

这应该使用GET request paramsurl.com/action?param=value

填充您的路线

如上所述,所有这一切的基础是,您没有发送变量,您将在当前控制器操作中初始化它,然后使用下一步行动叫它。