| Start |
|---|
| Polymorphic association This type of association allows an ActiveRecord model to belong to more than one kind of model record. Common example: Without this association, you’d have all these foreign keys in your Address table but you only would ever have a value for one of them because an address, in this scenario, can only belong to one entity (Human or Company). Here is what it would look like: |
| belongs_to A For example, if your application includes users and posts, and each post can be assigned to exactly one user, you'd declare the post model this way: In your table structure you might then have |
| Self-Referential Association Self-referential association is used to associate a model with itself. The most frequent example would be, to manage association between a friend and his follower. ex. now you can associate models like; and the other model will look like; |
| has_one A For example, if each user in your application has only one account, you'd declare the user model like this: In Active Record, when you have a Here in our example: In accounts table, there can only be one record with a particular user_id. If you try to associate one more account for the same user, it makes the previous entry's foreign key as null(making it orphan) and creates a new one automatically. It makes the previous entry null even if the save fails for the new entry to maintain consistency. |
| has_many A This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing users and posts, the user model could be declared like this: The table structure of If you want to get the list of all the published posts for the |
| The has_many :through association A For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this: |
| The has_one :through association A For example, if each |
| The has_and_belongs_to_many association A For example, if your application includes |
Read Article
https://develop.horje.com/learn/1434/reference