COMPSCI 169 Lecture Notes - Lecture 12: Referential Integrity, Foreign Key, Representational State Transfer
33 views2 pages

CS169: Software Engineering
October 14, 2013
Announcements
❏Complete mid semester survey
❏Sign up for face to face project meetings with GSI
Associations: Mechanics
❏models must have attribute for foreign key
❏ActiveRecord manages it, not you!
❏For one-to-many association:
❏Add has_many to owning model and belongs_to to owned model
❏Create migration to add foreign key to owned side that references owning side
❏Apply migration
❏rake db:test:prepare to regenerate test database schema
Through Associations
❏but what about multiple associations?
❏add multiple “has_many” and “belongs_to”
❏Moviegoerhas_many:reviews
❏Moviehas_many:reviews
❏Reviewbelongs_to:moviegoer
❏Reviewbelongs_to:movie
❏but how would we get all the movies reviewed by a moviegoer?
❏moviegoer: has_many:movies,:through=>:reviews
RESTful Routes for Associations
❏how to keep track of movie and moviegoer for each review?
❏need info at creation time
❏use nested RESTful routes:
❏resources:movies becomes resources:moviesdoresources
:reviewsend
❏access reviews by going “through” a movie
DRYing Out Queries with Reusable Scopes
❏stack scopes which will be evaluated lazily
❏i.e. Movie.for_kids.with_good_reviews(3)
Associations: Wrap-Up
❏associations are part of application architecture
❏can manipulate RDBMS foreign keys