6

I get input from first action, how can I pass the value to another action?

example_controller.rb

def first
  @first_value = params[:f_name]
end

def second
  @get_value = @first_value
end
Bye
  • 732
  • 8
  • 29

2 Answers2

8

You can't pass instance variables, because the second action is running in a new instance of the controller. But you can pass parameters...

def first
  @first_value = params[:f_name]
  redirect_to second_action_path(passed_parameter: params[:f_name])
end

def second
  @first_value = params[:passed_parameter]
  @get_value = @first_value
end

You can also use session variables which is how you typically store values for a user... Don't store entire objects just keys as session store is typically limited

def first
  @first_value = params[:f_name]
  session[:passed_variable] = @first_value
end

def second
  @first_value = session[:passed_variable] 
  @get_value = @first_value
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53
  • Thank you. Can I use a class variable @@ in class, first pass value to class variable, then assign this class variable to @get_value in the second method – Bye Oct 24 '16 at 22:27
  • Is there never going to be more than one user on your application? Then yes you can use a class variable... But if you have two or more users you're going to get clashes. Maybe what you need is `session` – SteveTurczyn Oct 24 '16 at 22:30
  • That is correct, multiple user will cause problem. Do you mean I can use both your first solution and session for many users situation? – Bye Oct 24 '16 at 22:37
  • Thanks a lot, great solution. – Bye Oct 24 '16 at 23:24
  • Hi Steve, I learnt something about session on Rails Guide. http://guides.rubyonrails.org/action_controller_overview.html#session .It says I can delete session by using session[:passed_variable] = nil. I hope to know when to do that and why should do that – Bye Oct 25 '16 at 00:12
  • `session` is retained for the entire user session. Maybe you want to use a session to remember that you came from action "A" when you entered action "B"... but the next time you enter action "B" you don't want it to behave the same way. So when you enter action "B", you check for the session, do what you have to do, and delete it. The next time you enter action "B", you check for the session and it's not there so you follow regular processing. – SteveTurczyn Oct 25 '16 at 06:19
0

In addition to Steve's answer, I just wanted to point out another way is to use the session.

Example

In controller:

session[:your_variable] = "A Great Title!"

then access it in the view:

<h1><%= session[:your_variable] %></h1>

More reading here, here, and here.

stevec
  • 41,291
  • 27
  • 223
  • 311