2011-02-01 24 views
0

启动信息:Rails3,Authlogic和authenticates_many如何编写current_account_session的辅助方法?

  • 我的系统没有用户子域名以获取正确的帐户!
  • 我使用的Rails 3.0.x的
  • 我使用authlogic 2.1.6
  • 模型帐户和模型用户
  • 存在Cookie与名称例如account_1_user_credentials这就对了!

型号Account.rb

class Account < ActiveRecord::Base 
    authenticates_many :user_sessions, :scope_cookies => true 
    has_many :users 
end 

型号User.rb

class User < ActiveRecord::Base 
    acts_as_authentic do |c| 
    c.validations_scope = :account_id 
    end 
    belongs_to :account 
    ... 
end 

问题:如何可以编写应用程序的辅助方法?

Authlogic的文档只显示不authenticates_many正常开展与scope_cookies:

class ApplicationController 
    helper_method :current_user_session, :current_user 

    private 
    def current_user_session 
     return @current_user_session if defined?(@current_user_session) 
     @current_user_session = UserSession.find 
    end 

    def current_user 
     return @current_user if defined?(@current_user) 
     @current_user = current_user_session && current_user_session.user 
    end 
end 

但如何session_controller.rb(设置current_account_session)application_controller.rb(实施高清current_account_session的.. 。end)长得怎样?

回答

2

如果所有用户都获得相同的登录信息,则需要根据current_user找到该帐户。为此,您不需要在帐户中使用authenticates_many。只需认证你的用户,然后得到它的帐户。

要设置你的控制器,看一下例子https://github.com/binarylogic/authlogic_example/blob/master/app/controllers/user_sessions_controller.rb

注意:您还可以检查的意见,...更多灵感。

这将允许您验证用户并管理它的会话。 登录后,您需要能够获取他的帐户,以便您可以为每个帐户的其他请求范围。

为了实现这一点,添加current_account是helper_method,通过添加以下到您的application_controller.rb

class ApplicationController 
    helper_method :current_account 

    private 

    def current_account 
     current_user.account 
    end 
    memoize :current_account 
end 

不要忘了还添加默认CURRENT_USER和current_user_session是helper_method。

这样,您可以随时在所有控制器中找到经过身份验证的用户的current_account。