简体   繁体   English

Mongoid accepts_nested_attributes_for当孩子无效时保存父母

[英]Mongoid accepts_nested_attributes_for saving parent when child is invalidwell

I am trying to use accepts_nested_attributes_for to create a User during the creation of an Organization . 我正在尝试在Organization创建期间使用accepts_nested_attributes_for创建User My problem is that the Organization is created (assuming it has valid information) even when the nested User information is invalid. 我的问题是,即使嵌套的User信息无效,也会创建Organization (假设Organization具有有效信息)。

My models look like this: 我的模型如下所示:

class Organization
  include Mongoid::Document

  attr_accessible :name, :users_attributes

  field :name, :type => String

  has_many :users, dependent: :destroy
  accepts_nested_attributes_for :users, :limit => 1

  validates_presence_of :name
end

class User
  include Mongoid::Document

  authenticates_with_sorcery!

  attr_accessible :email, :password, :password_confirmation

  field :email, type: String

  validates_confirmation_of :password, :if => :password
  validates_presence_of :password, :on => :create 
  validates :password, :length => { :minimum => 6 }
  validates_presence_of :password_confirmation, :if => :password
  validates_presence_of :email
  validates_uniqueness_of :email

  belongs_to :organization
end

So basically, I pass in a valid organization and an invalid user. 因此,基本上,我传入一个有效的组织和一个无效的用户。 The end result is that the organization is created properly despite the fact that the user information is invalid. 最终结果是尽管用户信息无效,也可以正确创建组织。 Thoughts? 有什么想法吗?

As it turns out, the issue here was that I wasn't specifying :autosave => true on my has_many :users association. 事实证明,这里的问题是我没有在has_many :users关联上指定:autosave => true The end result was that it would create the organization and never attempt to save the associated user, thus not knowing it was invalid. 最终结果是它将创建组织,并且从不尝试保存关联的用户,因此不知道它是无效的。 When i have the :autosave flag set to true and the user is invalid, the organization is not saved. 当我将:autosave标志设置为true并且用户无效时,将不保存组织。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM