Quick Guide to Nested Attributes in Rails
Model associations are an integral part of any Rails application. Nested attributes make it possible to save new instances of associated models through their relative. To accomplish this you must use the
accepts_nested_attributes_for method creates an attribute writer using the name of the association. Using the example above, the writer will be
albums_attributes=(attributes). This writer is then added to the permitted parameters for mass assignment.
Upon creation of a new Band instance, one or more Album instances will be created at the same time based on the parameters received from the form. The attribute writer method does not check if a model instance already exists with those attributes and will create a new instance. This is undesirable as multiple duplicate instances can crowd up the database. If there is potential for duplication then you must create your own attribute writer that accounts for this.
Now multiple new instances can be created and associated with their parent. By default if one of the children fails validation, the parent and any other children that pass validation will be created and saved to the database without it. What if you wanted to prevent the parent model from saving if one of their children fails validation? That’s where
validates_associated comes in. In the above example if one of the new album instances fails validation it will prevent the band from saving to the database.
That’s a quick rundown of nested attributes. These are a few of the methods and techniques every Rails developer should know for efficiently creating and associating new models.