2010-12-14 44 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