Associations
Crecto provides helper macros for defining associations between data models.
Has Many and Belongs To
Has Many options
through
- Specifying a join tabledependent: :destroy
- On deletion, will delete all associated records firstdependent: :nullify
- On deletion, will nullify all associated records foreign keysforeign_key
- Specify the foreign key field of of the associated tableforeign_key: :user_id
Has One
Has One options
dependent: :destroy
- On deletion, will delete all associated records firstdependent: :nullify
- On deletion, will nullify all associated records foreign keysforeign_key
- Specify the foreign key field of of the associated tableforeign_key: :user_id
Has Many Through / Join tables
Setting associations
Nil-check associations
If an association is not loaded, the normal accessor will raise an exception
For `has_many` preloads, the result will always be an array
For belongs_to
and has_one
preloads, the result may still be nil if no record exists. If the association is nullable, always use the association_name?
syntax.