Self 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!

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)

Standard has_many

  • has_many :quits
  • Inferred that
    • quits table exists
    • users_id on quits refers to the owning user's id

What if we want something different?

Do it manually!

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: :User, foreign_key: :a_id
    • know it's class and that user's id is the a_id column
  • belongs_to :user_b, class: :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
  • 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

Heroku

 

  • Easy web hosting
  • Currently free (not in the near future)