获取正确的current_page?在Rails路由中渲染匹配时

时间:2013-04-01 17:53:29

标签: ruby-on-rails

使用Rails 3.2。我正在使用current_page?来确定当前页面,以便将active添加到相应的导航链接。

当登录失败时,它会返回user_sessions#new,但current_page?不再识别login_path,因此不会将类active添加到链接中。

我无法使用redirect_to因为我想捕捉控制器中的错误。

如何让current_page?同时识别user_sessions#new

以下是我的代码:

# routes.rb
# Following 2 lines ensure that the login url is maintained as "login" even there are errors after submitting the form
match 'login' => 'user_sessions#new', :as => :login, :via => :get
match 'login' => 'user_sessions#create', :as => :login, :via => :post

# user_sessions_controller.rb
class UserSessionsController < ApplicationController  
  def create
    @user_session = UserSession.new(params[:user_session])
    if @user_session.save
      flash[:success] = "Login successful!"
      redirect_back_or_default profile_account_url
    else
      render 'new'
    end
  end
end

# _sub_nav.html.erb
<ul class="nav nav-tabs">
  <li<%= " class=active" if current_page?(login_path) %>>
    <a href="<%= login_path %>">Login</a>
  </li>
  <li<%= " class=active" if current_page?(signup_path) %>>
    <a href="<%= signup_path %>">Signup</a>
  </li>
</ul>

1 个答案:

答案 0 :(得分:1)

我相信改变

<li<%= " class=active" if current_page?(login_path) %>>

<li<%= " class=active" if current_page?(:controller => 'user_session', :action => 'new') %>>

应该有用。