如何使用redirect_to传递变量?

时间:2011-02-03 14:25:27

标签: ruby-on-rails ruby-on-rails-3

在我的控制器销毁功能中,我想在删除项目后重定向到索引,并且我想在重定向时传递一个名为'checked'的变量:

def destroy
    @Car = Car.find(params[:id])
    checked = params[:checked]

    if @car.delete != nil

    end

    redirect_to cars_path #I would like to pass "checked" with cars_path URL (call index)
end

如何通过 cars_path 传递这个'checked'变量,以便在我的索引函数中我可以得到它? ( cars_path 调用 index 函数)

def index
 checked = params[checked]
end

1 个答案:

答案 0 :(得分:49)

如果您不介意在网址中显示参数,您可以:

redirect_to cars_path(:checked => params[:checked])

如果你真的介意,你可以传递会话变量:

def destroy
  session[:tmp_checked] = params[:checked]
  redirect_to cars_path
end

def index
  checked = session[:tmp_checked]
  session[:tmp_checked] = nil # THIS IS IMPORTANT. Without this, you still get the last checked value when the user come to the index action directly.
end