Rails:如何在同一个控制器中将值从一个操作传递到另一个操作

时间:2016-10-24 21:34:01

标签: ruby-on-rails

我从第一个动作获得输入,如何将值传递给另一个动作?

example_controller.rb

def first
  @first_value = params[:f_name]
end

def second
  @get_value = @first_value
end

1 个答案:

答案 0 :(得分:4)

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