启动信息:
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的实现)是怎样的?
答案 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。