DEV Community

Kat
Kat

Posted on • Updated on

Industrial Grade Codebase: Associations and Validations

Some additional notes about ways you can modify your tables in your ActiveRecord migrations:

-You can use index: false to shut off indexing. This is useful because each index you add to your table increases how much storage space it takes up. This is especially important if the size of your table is large. Additionally, indexes slow down Create, Update, and Delete operations because the index needs to be updated along with the rest of that data.

-null: false makes it so that this column cannot be empty.

-You have to use a class_name: "Example" in your association in the case that you are deviating from convention. Conversely, you use `foreign_key: "example_id" when the foreign key deviates from convention. Class_name specifies the model you are connecting to with the association, whereas foreign_key specifies the column in the table that connects to the model.

Association Accessors

belongs_to

belongs_to is a direct association accessor. It adds an automatic validation to foreign key columns making a foreign key required unless you override this by adding optional: true. If you remove null: false from any foreign key column in the migration file, you must add optional: true to the corresponding belongs_to.

counter_cache

counter_cache can be added to any belongs_to to keep track of the number of children objects.

Top comments (0)