Created
October 4, 2017 05:42
-
-
Save anoobbava/010d8d4c92041fcfc49983de0df65b17 to your computer and use it in GitHub Desktop.
Association Examples in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1.belongs_to association: | |
--------------------- | |
- Student and College: | |
- a student belongs_to college | |
- college_id is present in the college | |
- Example: | |
************** | |
class Student < ApplicationRecord | |
belongs_to :college | |
end | |
migration file | |
************** | |
add_column :students, :college_id, :integer | |
2.has_many association: | |
--------------------- | |
- student and college | |
- college has many students | |
- Example: | |
************** | |
class College < ApplicationRecord | |
has_many :students | |
end | |
3. has_one association: | |
----------------------- | |
- student and profile | |
- each student has a profile. | |
- Example | |
************** | |
class Student < ApplicationRecord | |
has_one :profile | |
end | |
class Profile < ApplicationRecord | |
belongs_to :student | |
end | |
- student_id in profiles table. | |
4. has_many through association: | |
------------------------------- | |
- very important association | |
- many students applied for many companies | |
- many companies receives application from many students | |
- Example | |
********** | |
class student < ApplicationRecord | |
has_many :applications | |
has_many :companies, through: applications | |
end | |
class Company < ApplicationRecord | |
has_many :applications | |
has_many :students, through: applications | |
end | |
class Application < ApplicationRecord | |
belongs_to :student | |
belongs_to :company | |
end | |
- here the applications table contain the student_id and company_id | |
5. has_one :through association | |
------------------------------- | |
- here student has a profile and profile_history | |
- here one to one association | |
- Example: | |
************ | |
class Student < ApplicationRecord | |
has_one :profile_history | |
has_one :profile, through: profile_history | |
end | |
class Profile < ApplicationRecord | |
has_one :profile_history | |
has_one :student, through: profile_history | |
end | |
class ProfileHistory < ApplicationRecord | |
belongs_to :profile | |
belongs_to :student | |
end | |
6. has_and_belongs_to_many | |
-------------------------- | |
- rarely used | |
- Example: | |
*********** | |
class Student < ApplicationRecord | |
has_and_belongs_to_many :companies | |
end | |
class Company < ApplicationRecord | |
has_and_belongs_to_many :students | |
end | |
- Create a table Application or adding a reference keys student_id, company_id to Application table. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment