1

假设我有这些:

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")
    }
  ]
}

为了实际保存提供的数据,我需要做什么?和总是正确地在uid数组中,我检查了。providerauth

4

2 回答 2

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
于 2013-04-30T06:21:59.553 回答
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
于 2013-04-30T06:21:31.620 回答