简体   繁体   English

将变量从控制器传递到轨道4中的视图

[英]passing a variable from controller to view in rails 4

I want to pass a variable value from controller to view as shown below 我想将一个变量值从控制器传递给视图,如下所示

controller (.rb) 控制器(.rb)

redirect_to root_url, :some_var => 'true or false'

view (root_url.html.erb) view(root_url.html.erb)

<% if :some_var %>
   #do something
<% else %>
   #do something else.

can anyone provide me an idea. 任何人都可以给我一个想法。 Thanks in advance. 提前致谢。

Then just pass that variable as query string 然后将该变量作为查询字符串传递

redirect_to root_url(foo: 'bar')

This will produce url like 这会产生url之类的

example.com?foo=bar

Another way is to use flash object 另一种方法是使用flash对象

redirect_to root_url, notice: "This is some info to convey"

Flash to convey temp variable: Flash传递临时变量:

flash[:foo] = 'bar'
redirect_to root_url

# View
<% if flash[:foo] %>
  <%= "This is #{flash[:foo]} value" %>

the best way to do this is to render, not redirect, since you're not quite finishing the whole action. 这样做的最好方法是渲染,而不是重定向,因为你还没有完成整个动作。 then just use instance variables in the controller action: 然后在控制器动作中使用实例变量:

@some_var = true or false
render root_url

root: 根:

if @some_var 
   do blah

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM