Mongoid没有为' belongs_to'保存nested_attributes。以1:1的关系

时间:2012-03-19 20:03:01

标签: ruby ruby-on-rails-3 mongoid

我有两个型号的联系人和用户。当我创建新用户时,我正在尝试同时创建联系人。但它并没有因某种原因而被创造出来。关于为什么的任何想法?

class Contact
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes
  include Mongoid::Paranoia
  include Mongoid::Versioning

  # Attr.
  attr_accessible :first_name, :last_name, :birthday, :email_addresses_attributes, :phone_numbers_attributes, :relationships_attributes, :addresses_attributes

  #Relationships
  belongs_to :firm, validate: true
  has_one :user # contact information for user
  has_many :relationships, autosave: true
  has_many :clients
  has_many :notes, dependent: :destroy
  ...
end


class User
  include Mongoid::Document
  include ActiveModel::SecurePassword
  include Mongoid::Timestamps

  # Attr.
  attr_accessible :contact_id, :contact_attributes, :password, :password_confirmation, :google_tokens

  #Relationships
  belongs_to :firm, validate: true
  belongs_to :contact, validate: true, autosave: true
  has_one :user_type
  embeds_many :histories

  # Nested Attrs
  accepts_nested_attributes_for :contact
  ...
end

1 个答案:

答案 0 :(得分:0)

accepts_nested_attributes_for在所有者对象上完成,允许您设置属于它的对象的属性。

在您的情况下,用户属于(或嵌套在)联系人。您必须在联系人模型中执行accepts_nested_attributes_for :user

您可以切换它以便用户has_one :contact和联系人belongs_to :user。这需要您给Contact一个user_id字段。