Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby Mongoid嵌入文档的类方法_Ruby_Mongoid - Fatal编程技术网

Ruby Mongoid嵌入文档的类方法

Ruby Mongoid嵌入文档的类方法,ruby,mongoid,Ruby,Mongoid,我希望将所有特定于身份验证的代码保存在定义身份验证“模型”的文件中,如下所示: 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(u

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

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
模型中的单例方法不是一个好主意?

您不能像第一次尝试的那样直接访问嵌入式文档
Auth.loggin('user','pass')
。在这样的嵌入式文档模型中,应该只有实例方法

def self.login(user, pass)
   User.first(conditions: { username: user, password: pass })
end
@user.auth.login('user','pass')
并且可以像这样通过用户对象访问它

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