2008-10-23 56 views
5

所以,我對於登錄獲取渲染認識到定製的路由路徑

# routes.rb 
map.login '/login', :controller => 'sessions', :action => 'new' 

訪問www.asite.com/login時髦的定製路線,你在那裏。但是,如果用戶登錄失敗,我們會在我們的操作中執行以下操作。注意登錄失敗時會發生什麼。

# sessions_controller.rb 

def create 
    self.current_user = User.authenticate(params[:email], params[:password]) 
    if logged_in? 
    # some work and redirect the user 
    else 
    flash.now[:warning] = "The email and/or password you entered is invalid." 
    render :action => 'new' 
    end 
end 

這是非常典型的。只需呈現新操作並提示再次登錄。不幸的是,你也會得到一個醜陋的網址:www.asite.com/session。伊克!是否有可能得到渲染尊重原始網址?

+1

不好的例子。考慮你希望用戶已經填寫到表單中的文本被保留的情況。渲染是這樣做的(因爲對象是部分構建的)。重定向失去狀態。 – 2008-10-23 21:45:46

回答

0

變化render :action => 'new'redirect_to login_path

7

你的問題是這樣的:用戶首先訪問/login,並在填寫表單。當他們提交表單時,他們發佈到/sessions,這就是瀏覽器URL更改的原因。爲了解決這個問題,你可以做兩件事情:

正如邁克爾所說,你可以回重定向到新的動作,改變了別的:

else 
    flash[:warning] = "The email and/or password you entered is invalid." 
    redirect_to login_path 
end 

請注意,你需要改變閃光因此該消息在下一個請求中可用(在重定向之後)。

第二種方法稍微有點黑,但也許值得一提。通過在路由中使用條件,可以將登錄表單(這是一個GET)和表單submit(這是一個POST)映射到相同的路徑。例如:

map.login '/login', 
    :controller => 'sessions', :action => 'new', 
    :conditions => {:method => :get} 

map.login_submit '/login', 
    :controller => 'sessions', :action => 'create', 
    :conditions => {:method => :post} 

然後,如果您的表單操作是登錄提交路徑,則事情應該按照您的預期工作。