2

I have two models

class Person
  embeds_one :address
end

class Address
  embedded_in :person
  field :city
  validates :city, :presence => true
end

Now when I do

person.address = Address.new

the validation of address is called. But I don't need the validation in my case and neither can I remove :validates from Address (because I need it later on). I want to do something like (:validate => false). If anybody got idea, let me know! I am using mongoid-2.0.0.

Sadiksha Gautam
  • 5,032
  • 6
  • 40
  • 71

3 Answers3

1

You can use

person.address = Address.create

then the validation is not called I believe. When you update the record and finally save it, the validation is called. It is also possible to use something like

person.address = Address.new :addres => "Valid address"

and the validation will not fail.

Turning the validation on and off, seems weird to me as this results in invalid addresses in the database... You could change your validation routine to accept empty addresses as well if such addresses are is the problem.

Veger
  • 37,240
  • 11
  • 105
  • 116
  • 1
    It id not work, I tried the first option and I got this error "Access to the collection for Address is not allowed since it is an embedded document, please access a collection from the root document". I also tried the 2nd option, but didn't work. Actually I need to save an intermediate address before saving the final address. That is why I an trying to turn validation off. – Sadiksha Gautam Apr 04 '11 at 11:10
  • Your error is found on the web lots of times and it seems to be a mongoid issue, see this SO question as well: http://stackoverflow.com/questions/5069315/how-to-fabricate-mongoid-document-with-embedded-document-using-fabrication – Veger Apr 04 '11 at 14:25
  • 1
    yeah it is for embeds_many but in I did not find the errors with embeds_one.... also the embedded document is saved but the errors are still displayed. – Sadiksha Gautam Apr 06 '11 at 05:21
1

I believe what you want is:

address = person.build_address

or simply:

person.build_address

Refer to the "building and creating" section.

astjohn
  • 2,922
  • 1
  • 22
  • 25
0

What about creating a custom address validator, and have it check to see if it is a new record. if it is then it is still valid with an empty email?