For example, consider a simple Rails application that includes a model for authors and a model for books. Without associations, the model declarations would look like this: With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models.
Because they make common operations simpler and easier in your code.
Rails supports six types of associations: another, you instruct Rails to maintain Primary Key-Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model.
In the remainder of this guide, you'll learn how to declare and use the various forms of associations.
But first, a quick introduction to the situations where each association type is appropriate.
A association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model.
For example, if your application includes authors and books, and each book can be assigned to exactly one author, you'd declare the book model this way: model, you would be told that there was an "uninitialized constant Book:: Authors".
This is because Rails automatically infers the class name from the association name.
If the association name is wrongly pluralized, then the inferred class will be wrongly pluralized too.
association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences).
This association indicates that each instance of a model contains or possesses one instance of another model.
For example, if each supplier in your application has only one account, you'd declare the supplier model like this: Depending on the use case, you might also need to create a unique index and/or a foreign key constraint on the supplier column for the accounts table.
In this case, the column definition might look like this: association.