在Mongoid中创建关于对象创建的嵌入式文档

时间:2013-04-30 06:12:23

标签: ruby-on-rails ruby mongodb mongoid

让我说我有这些:

class User
  include Mongoid::Document
  field :name, type: String
  field :email, type: String
  embeds_many :auths

  attr_protected :name, :email
end

class Auth
  include Mongoid::Document

  field :provider
  field :uid

  embedded_in :user

  attr_protected :provider, :uid
end

我使用此方法创建一个新用户:

  def self.create_with_omniauth(auth)
    create! do |user|
      user.auths.build(provider: auth['provider'], uid: auth['uid'])
      if auth['info']
        user.name = auth['info']['name'] || ''
        user.email = auth['info']['email'] || ''
      end
    end
  end

但是,当我查看我的数据库时,结果如下:

{
  "_id" : ObjectId("517f5f425aca0fbf3a000007"),
  "name" : "User",
  "email" : "mail@example.com",
  "auths" : [
    {
      "_id" : ObjectId("517f5f425aca0fbf3a000008")
    }
  ]
}

为了实际保存提供的数据,我该怎么办?我检查了uidprovider总是正确地放在auth数组中。

2 个答案:

答案 0 :(得分:2)

目前只跳过属性,因为这就是你告诉Rails的内容

要么改变:

attr_protected :provider, :uid

为:

attr_accessible :provider, :uid

或按以下步骤操作:

user.auths.build.tap do |user_auth|
  user_auth.provider = auth['provider']
  user_auth.uid      = auth['uid']
end

答案 1 :(得分:1)

你能试试吗?

def self.create_with_omniauth(auth)
  create! do |user|
    auth = Auth.build(provider: auth['provider'], uid: auth['uid'])
    if auth['info']
      user.name = auth['info']['name'] || ''
      user.email = auth['info']['email'] || ''
    end
    user.auths << auth
  end
end