开发者

set validation false on association mongoid

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 validatio开发者_运维问答n 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.


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.


I believe what you want is:

address = person.build_address

or simply:

person.build_address

Refer to the "building and creating" section.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜