atchyutn / railsAssociations

Rails Association examples
MIT License
0 stars 0 forks source link

Update README File #1

Open atchyutn opened 5 years ago

atchyutn commented 5 years ago

Feature Request Add installations setups, Usage Examples

Solution Description Add Usage Instructions, Examples that can be run in the rails console.

atchyutn commented 5 years ago

Sample Usage Examples:

belongs_to & has_many association: Relation: User-> has_many posts Post-> belongs to user

creation: user = User.new user.name = "Karthik" user.save

post = Post.new post.title = "First post" post.user_id = user.id post.save

Results: User.find(user.id).posts-> posts Post.find(post.id).user-> user


one-to-one association: User has_one address Address belongs_to user

creation: user = User.new user.name = "Karthik" user.save

address = Address.new address.city="Hyderabad" Address.find(address.id).user_id = user.id

User.find(user_id).address Address.find(address_id).user


Many-to-Many Association: Has and belongs to many associations: Relation: User -> has_and_belongs_to_many :events Event-> has_and_belongs_to_many :users

Creation: e1 = Event.new e1.title = "Event one" e1.save

e2 = Event.new e2.title = "Event two" e2.save

user = User.new user.name = "Karthik" user.save

user.events << e1 user.events << e2

Result: user.events -> e1, e2 e1.users -> u1, u2


Has Many through association: Relations: Enrollment-> belongs_to :game, belongs_to :user User->has_many :enrollments, has_many :games, through: :enrollments Game->has_many :enrollments, has_many :users, through: :enrollments

Creation: g1 = Game.new g1.title = "GTA" g1.save

u1 = User.new u1.name = "Karthik" u1.save

e1 = Enrollment.new e1.game_id = g1.id e1.user_id = u1.id e1.category = "firing games" e1.save

Result: u1.enrollments -> e1 g1.enrollments -> e1 e1.category-> firing games


Has One through Association: Relations: User->has_one :wallet, has_one :payment_history, through: :wallet Wallet->belongs_to :user, has_one :payment_history PaymentHistory->belongs_to :purse

Creation:

user = User.new user.name = "Karthik" user.save

wallet = Wallet.new wallet.funds = 100 wallet.user_id = user.id wallet.save

ph = PaymentHistory.new ph.wallet_id = wallet.id ph.save

Results: user.payment_history-> ph user.wallet->wallet wallet.user->user