Pregunta

I'm still getting my head around MongoDB and Mongoid in particlar.

Let's say I have a User and each User has one Thingamajig. When I create the User I want the system to autmatically also create a blank Thingamajig for that User.

Each Thingamajig has a whatsit field that must be unique if it has a value, but is allowed to have no value when created.

So I define the following classes.

class Thingamajig
  include Mongoid::Document
  field :whatsit, type: String
  index({whatsit: 1}, {unique: true, name: 'whatsit_index'})
end

class User
  include Mongoid::Document
  field :name, type: String
  index({name: 1}, {unique: true, name: 'user_name_index'})
  embeds_one :thingamajig, dependent: :nullify, autobuild: true
end

However what I find when I

User.create!(name: 'some name')

is that User.find(name: 'some name').thingamajig is nil.

Questions:

  1. How can I ensure that each User gets an associated Thingamajig? and
  2. How do I specify that the name field of a User is required?

FYI I am using Sintara not Rails (if that matters to anyone).

¿Fue útil?

Solución

1 - The autobuild: true option normally should have done the trick. I think the problem is that you forgot to add the other side of the relation to the Thingamajig model:

class Thingamajig
  include Mongoid::Document
  embedded_in :user
  ...
end

2 - To specify required fields, use validations:

class User
  include Mongoid::Document
  field :name, type: String
  validates_presence_of :name
  ...
end

Mongoid uses ActiveModel validations.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top