验证mongoid中的关系invalids

时间:2014-07-18 19:17:20

标签: mongoid

class A
  include Mongoid::Document

  field :value, type: String
  validates :value, presence: true

  has_and_belongs_to_many :cs
end

class B
  include Mongoid::Document

  belongs_to :a
  embedded_in :c
end

class C
  include Mongoid::Document

  embeds_many :bs
end

c = C.create #<C _id: 53c96d1f05dfd40943000001, >
c.valid? # true

a = A.create #<A _id: 53c96d8305dfd4b6e1000002, value: nil, c_ids: nil>
a.valid? # false

invalid_b = c.bs.create(a: a) #<B _id: 53c96dac05dfd4b6e1000004, a_id: "53c96d8305dfd4b6e1000002">

# Invalid object has created !!!!!
# a not been persisted but the c saved his id.

invalid_b.reload
invalid_b.a # nil
invalid_b.a_id # 53c96d8305dfd4b6e1000002

“a”字段无效,但正在创建“b”。 我怎么解决这个问题? 那么类“B”在保存前验证字段?

1 个答案:

答案 0 :(得分:0)

如果您使用

invalid_b = c.bs.create!(a: a)

而不是

invalid_b = c.bs.create(a: a)

无效记录无法创建,create!将引发Mongoid::Errors::Validations例外

检查http://mongoid.org/en/mongoid/docs/persistence.html以获取参考