Reputation: 6041
I'd like to keep all authentication specific code in the file that defines the Auth "model" like this:
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
The problem? It's not possible to call class methods of embedded documents:
> 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
Singleton methods in embedded Mongoid::Document
models is not a good idea?
Upvotes: 3
Views: 967
Reputation: 5213
You can't access embedded documents directly like you tried first time Auth.loggin('user','pass')
. You should be having only instance methods in embedded document models like this
def self.login(user, pass)
User.first(conditions: { username: user, password: pass })
end
and can access it by user object like this
@user.auth.login('user','pass')
Upvotes: 1