2012-01-10 50 views
2

窥视这个简化的认证系统:类方法嵌入文档

class User 
    include Mongoid::Document 
    embeds_one :auth 
    field :username, type: String 
end 

class Auth 
    include Mongoid::Document 
    embedded_in :user, inverse_of: :auth 
    field :password 

    def self.login(user, pass) 
    User.first(conditions: { username: user, password: pass }) 
    end 
end 

为什么?因为我想在定义Auth“模型”的文件中保留所有身份验证特定的内容。

问题?无法调用嵌入式文档的类方法:

> Auth.login('user', 'pass') 
Mongoid::Errors::InvalidCollection: Access to the collection for Auth is not allowed since it is an embedded document, please access a collection from the root document. 

> User.auth.login('user', 'pass') 
NoMethodError: undefined method `auth' for User:Class 

那么,嵌入式文档模型中的类方法,不是一个好主意吗?

回答

1

您不能像第一次尝试Auth.loggin('user','pass')那样直接访问嵌入式文档。你应该有这样的

def self.login(user, pass) 
    User.first(conditions: { username: user, password: pass }) 
end 

中嵌入文档模型只实例方法,可以通过用户对象这样

@user.auth.login('user','pass') 
访问