Lighthouse W3D2 – Octopi And Mice

Today we learned about Object Relational Mapping and built mini ORMs. We connected to our postgres database using the pg gem, and then wrote SQL queries that were sent through the connection with exec_params. We created class and instance methods for a Contact class, including Create Read Update Delete commands. A few hours later, we learned about ActiveRecord. This was my brain during the entire break out session… (but outwardly, only slightly bewildered). Learning ActiveRecord...

Rails pluralizes your class names to find the appropriate database tables
This means that your classnames go from CamelOctopus –> camel_octopi table, Mouse –> mice table, Sheep –> sheep table… WHOA, magic! Alright, not magic, it’s Ruby code, but pretty amazing.

Why ActiveRecord is awesome:

– No more SQL queries! (Ok so I actually liked the SQL exercises from yesterday, but I’m more than happy to let ActiveRecord do it instead…)

– All you have to do is subclass an ActiveRecord::Base, and you’ve got a model that maps to a table in the database (Example: class Person < ActiveRecord::Base end, this maps to the ‘people’ table in the database. Yes, it knows to change person to people. It’s crazy.)

– ActiveRecord creates methods for you to easily do CRUD(Create, Read, Update, Delete) operations. You can just call .create to create and save a new record to the database… goodbye ‘painful writing to a CSV file’!

– You can use .find_by to find one result, and .where to find many results

– Once an ActiveRecord object has been found, you can call the .update method to change an attribute and save the record to the database in one function call.

– You can validate the state of a model before it is saved to the database through validations
– You can use has_one, has_many, belongs_to to easily map relations between tables!

Summary: Today was another example of doing things ‘the Lighthouse way’: we do it ‘manually’ or ‘the hard way’, and then we learn a better and easier way. I was impressed with the pg gem after struggling with the CSV file last week, then ActiveRecord just blew my mind!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s