简体   繁体   中英

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)

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

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

example.com?foo=bar

Another way is to use flash object

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

Flash to convey temp variable:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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