mlovic
mlovic

Reputation: 864

Mongoid: how to set embedded object (embeds_one relation) without persisting

Say I have the two models:

class Person
  include Mongoid::Document
  embeds_one :address
end

class Address
  include Mongoid::Document
  embedded_in :person
end

I am trying to set the address of a created person, without the address being persisted to the database.

person.address = Address.new # Automatically persists address to the database.

My question is basically the same as this one, except this is an embeds_one relationship, so the build method is not available. I have seen the dynamically created build_<embedded_object> method, but it does not seem to accept the same options as build, namely the specific class with which to build the embedded object (it's a subclass of the associated class):

person.posts.build({
  name: "Another post"
}, SpecialPost)
# Works

person.build_address({
  name: "An address"
}, SpecialAddress)
# Does not work

Upvotes: 2

Views: 1261

Answers (1)

Kevin Li
Kevin Li

Reputation: 2114

The address embeded in person will not be persist by default, when you run

Person.new(...)

It will be persist only if you add autobuild to be true

embeds_one :address, autobuild: true

and also set

validates_presence_of :address

The latter will make sure it will be persist in database.

Or you could assign address to person object without saving it.

Upvotes: 1

Related Questions