Mongoid嵌入式文档的类方法

时间:2012-01-10 14:17:33

标签: ruby mongoid

我想将所有特定于身份验证的代码保存在定义Auth“模型”的文件中,如下所示:

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.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

嵌入式Mongoid::Document模型中的单例方法不是一个好主意吗?

1 个答案:

答案 0 :(得分:1)

您无法像第一次尝试Auth.loggin('user','pass')那样直接访问嵌入式文档。您应该只在嵌入式文档模型中使用实例方法,如此

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

并可以通过像这样的用户对象访问它

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