-
Notifications
You must be signed in to change notification settings - Fork 2
Database Layout (Relationships)
My favorite part of programming is organizing logical associations. When I learned how to create arrays within objects, it was pretty cool. Collections were pretty awesome too. I'm speaking of implementations like...
me = Warrior.new(name: "TheNotary")
me.inventory << Item.new(name: 'Potion')
me.inventory << Item.new(name: 'Magic Feather')
me.inventory[0]
# => <Item: name: 'Potion'>
So being able to actually save objects that contain arrays like that, we would look to a database. Conventional databases represent data in tables. One record in the warriors table might represent me. One record in the items table might represent a potion.
=warriors table=
id | name | hp | exp
13 'njax' 10 133
=items table=
id | warrior_id | name
10 13 'Potion'
11 13 'Magic Feather'
Notice how all the items that belong to me have my warrior_id? That's all it takes to from the has_many/ belongs_to association.
Ask me how to implement this in the models.
Ask me how to implement this in the views with a form.
But perhaps we would instead use a through table to create representations of an item from the items table being in my inventory. Other warriors might create references to them having that item in their inventory too. See below, a has many through table (which is a little advanced).
=warriors table=
id | name | hp | exp
13 'njax' 10 133
=items table=
id | name
10 'Potion'
11 'Magic Feather'
=inventory table=
warrior_id | item_id
13 10
13 11