2010-12-14 80 views
5

我没有找到如何做到这一点,即使有很多的建议,就如何PARAMS通过使用hashs这样redirect_to的轨道3 redirect_to的传递PARAMS到一个名为路线

:action => 'something', :controller => 'something' 

重定向很多信息在我的应用我在路由的以下文件

match 'profile' => 'User#show' 

我的表演动作洛斯这样

def show 
@user = User.find(params[:user]) 
    @title = @user.first_name 
end 

重定向发生在同一个用户控制器这样

def register 
    @title = "Registration" 
    @user = User.new(params[:user]) 

    if @user.save 
     redirect_to '/profile' 
    end 
    end 

的问题是,在寄存器行动时,我redirect_to的我怎么沿PARAMS传递这样我就可以抓住从数据库或更好的用户...我已经有一个用户变量,所以如何将用户对象传递给show动作?

马修

回答

7

如果你正在做一个重定向,Rails会实际发送一个网址到浏览器,浏览器将发送另一个请求到该URL一个302 Moved响应。所以你不能像在Ruby中那样“传递用户对象”,你只能传递一些url编码参数。

在这种情况下,你可能会想你的路由定义修改为:

match 'profile/:id' => 'User#show' 

,然后重定向这样的:

redirect_to "/profile/#{@user.id}" 
+0

工作完美!非常感谢你的帮助 – mattwallace 2010-12-14 16:50:16

2

首先,我命名你的路线,使使用它更容易:

match '/profile/:id' => 'users#show', :as => :profile 

然后你会重定向到它,如下所示:

redirect_to profile_path(@user) # might have to use profile_path(:id => @user.id) 

然后从数据库中提取用户:

def show 
    @user = User.find(params[:id]) # :id comes from the route '/profile/:id' 
    ... 
end 

顺便说一句,如果你使用类似设计进行验证,它为您提供了CURRENT_USER方法,因此你不会需要传递用户的ID:

match '/profile' => 'users#show', :as => :profile 

redirect_to profile_path 

def show 
    @user = current_user 
end