Rails3,Authlogic和authenticates_many如何编写current_account_session辅助方法?

时间:2011-02-01 14:18:12

标签: ruby-on-rails-3 cookies authlogic scope-identity

启动信息:

  • 我的系统没有用户子域来获得正确的帐户!
  • 我使用Rails 3.0.x
  • 我使用authlogic 2.1.6
  • 模型帐户和模型用户
  • Cookie以名称出现,例如account_1_user_credentials,那就对了!

Model Account.rb

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

Model User.rb

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

问题:如何编写应用程序帮助程序方法?

Authlogic的文档仅显示没有带scope_cookies的authenticates_many的正常实现:

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(def current_account_session ... end的实现)是怎样的?

1 个答案:

答案 0 :(得分:2)

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

要设置控制器,请查看示例https://github.com/binarylogic/authlogic_example/blob/master/app/controllers/user_sessions_controller.rb

注意:您还可以查看视图,...以获得更多灵感。

这将允许您对用户进行身份验证并管理其会话。 登录后,您需要能够获得他的帐户,因此您可以为每个帐户设置其他请求。

要实现此目的,请通过将以下内容添加到application_controller.rb来添加current_account helper_method

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。