1

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.

1

2 Answers 2

3

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" %>
Sign up to request clarification or add additional context in comments.

3 Comments

But how to check the value of foo in view or template.
Can I use anything else than flash. Or may be just :foo
That's nice. flash has benefit that it got removed in next request. However, please still be aware of this pattern and not abuse session/flash :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.