Joins and Heroku
Hackathon:
Design For Good
This Saturday, starting at 4 PM
ending on Sunday at noon
Located in the Woz
Prizes for best beginner hacks too!
Logistics
Make sure you check in with your TA!
If you don't have a group or a TA hasn't emailed you let us know ASAP.
Joins
How to do more complicated relationships we didn't cover.
Heroku
How to host your apps on the internet so anyone can access it.
Joins
- We learned has_one, belongs_to, and has_many
- What if we do something that is not standard?
- Example modeling friendships(a join of a user and user)
- What if a pokemon belongs to more than one trainer?
Standard has_many
- has_many :quits
- Within user model
- Inferred that
- quits table exists
- users_id on quits refers to the owning user's id
Join Tables
- Use pets as an example
- If a pet had a single owner we can simple have
- User
- has_many :pets
- Pet
- belongs_to :user
- pet has a user_id column
- User
What if a pet is owned by multiple users?
- What about creating multiple rows in the pet table, with multiple entries for the same pet, each with a different user_id? Problems?
- Any other ideas?
Create a Join Table
- A users_pets table
- Each row in this table represents a pet ownership
- The users_pets table contains a user_id and a pet_id
- In user.rb just have
- has_and_belongs_to_many :pets
- In pet.rb just have
- has_and_belongs_to_many :users
- Rails will infer a users_pets table and get the associated records
Self Join For Users: Friendships
- Initial Problem, we can't say belongs_to :user
- reference two users
- Separate them into two references
- belongs_to :user_a
- belongs_to :user_b
- Problem: it will infer tables user_as and user_bs
Use foreign_key
- belongs_to :user_a, class_name: :User, foreign_key: :a_id
- know it's class and that user's id is the a_id column
- belongs_to :user_b, class_name: :user, foreign_key: :a_id
- now we can distiguish
Listing the users friendships
- has_many :friendships
- assumes friendships table and friendship class
- is the user user_a or user_b?
- has_many :friendships, foreign_key: :a_id
- specifies the user calling the method has the id a_id
Listing all the users friends
- One way is to define a function
- def friends
- friendships.map(:user_b).flatten
- def friends
- Can define as a relationship
- has_many :friends, through: :friendships, source: :user_b
- through - another relationship we want to reference
- source - method called on each
- in the end flattened
- has_many :friends, through: :friendships, source: :user_b
Heroku
- Easy web hosting
- Currently free (not in the near future)
Fall Week 9: Self Joins, Heroku
By Rails Decal
Fall Week 9: Self Joins, Heroku
- 1,011