W3D3 - The beauty of Active Record
The mystery of Active Record unfurled today as we dove straight into associations. Associations are a phenomenal tool that lets you use the power of SQL with the flexibility of Ruby and the magic of Rails.
The most common associations we used were has_many and belongs_to. Since we're just staring out with associations, we explicitly stated all of the information even if Rails would have picked up on it automatically. To give you a snippet - class User < ActiveRecord::Base
has_many( :submitted_urls, class_name: "ShortenedUrl", foreign_key: :submitter_id, primary_key: :id ) end
class ShortenedUrl < ActiveRecord::Base
belongs_to( :submitter, class_name: "User", foreign_key: :submitter_id, primary_key: :id ) end
This sets up a one to many relationship between our User and ShortenedUrl classes. Since our shortened_urls table has a foreign key pointing to to the users table, we use the belongs_to association in the ShortenedUrl class - this has counterintuitively been an easier way to think about it than 'A user can have many links,' especially as we moved on to more complicated has_many through associations.
While we still have to understand the SQL behind the magic of Active Record in order to use it, it clearly and quickly defines incredibly useful relationships.
The example above is from a command line url shortener we created today. It saves links, shortens them, and can be directly opened from the terminal. It also keeps track of the most popular links, can show all of a user's submitted links, and we implemented the basics of a tagging system. It was a great feeling getting a lot of functionality from a ~4 hour exercise!











