【问题标题】:Mongoid accepts_nested_attributes_for saving parent when child is invalidwellMongoid 接受_nested_attributes_for 在孩子无效时保存父母
【发布时间】:2012-01-12 19:53:44
【问题描述】:

我在创建Organization 期间尝试使用accepts_nested_attributes_for 创建User。我的问题是即使嵌套的User 信息无效,也会创建Organization(假设它具有有效信息)。

我的模型如下所示:

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

所以基本上,我传入了一个有效的组织和一个无效的用户。最终结果是,尽管用户信息无效,但仍能正确创建组织。想法?

【问题讨论】:

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


    【解决方案1】:

    事实证明,这里的问题是我没有在我的 has_many :users 关联中指定 :autosave => true。最终结果是它将创建组织并且从不尝试保存关联的用户,因此不知道它是无效的。当我将 :autosave 标志设置为 true 并且用户无效时,不会保存组织。

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 2014-10-27
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      相关资源
      最近更新 更多