First let's write the Author
model. We do it as follows:
class Author include Mongoid::Document field :name, type: String validates_presence_of :name has_one :address, as: :location, autosave: true, dependent: :destroy has_many :books, autosave: true, dependent: :destroy accepts_nested_attributes_for :books, :address, allow_destroy: true end
An author has many books and has one address. This is declared as follows:
class Author
...
has_many :books, autosave: true, dependent: :destroy
has_one :address, as: :location, autosave: true, dependent: :destroy
...
end
We have already seen relationships via Mongoid, but here are a few more options:
:autosave:
This option is specified in the parent model and enables its associated child objects to be saved along with the parent:as:
This is the polymorphic relation:dependent:
This option is also specified on the parent model and ensures that the dependent child objects are destroyed when the parent is destroyedWhen we are creating an author, we would also like to update all the books written by the author as well as update his address. We do this by accepting nested attributes:
class Author
...
accepts_nested_attributes_for :books, :address, allow_destroy: true
...
end
As the name suggests, accepts_nested_attributes_for
accepts nested attributes for the child relation.
We can only accept nested attributes for children. That means we should use them only in the parent relation.
We shall see how this comes into play when we build the Views.
Update the Author
model as follows:
class Author
...
validates_presence_of :name
...
end
Because this is a Mongoid document, it has all the features that are available with ActiveModel
, such as ActiveModel::Validations
. So we can use all the available validations here. In this case, we validate the presence of the name
to ensure that an Author
object is not created without the name!
3.22.236.249