Rails Active Record and SQL Queries

I’ve had this drafted for awhile but I’ve forgotten to post it so here it goes anyways …

These past few weeks have been focused on learning MySQL and active record methods. There are two types of databases which contain all other subtypes: SQL and noSQL. Class time has been focused on learning only SQL, specifically MySQL. We’ve also learned how to convert data from SQLite to MySQL as well installing SQL to our Rails projects. Making basic database queries isn’t too challenging, it’s when multiple tables need to speak together that things can get tricky.

As expected you’re probably not going to get your databases’s fields right on the first go. So we also learned how to migrate new columns in, how to remove them, and how to change the type of the column ie does the column contain a string, text, etc.

How does this get tied into Rails?

Rails Active Record essentially covers how your Rails application can communicate with your server. Through Rails you are able to query your database within your own application. This is often done as a method to your classes in the controller. As far as querying a MySQL database, the commands look very similar to how you would write a query in SQL.

Ordering a list of items alphabetically for this Recipe class would look like:

Recipe.order(author: :desc)

Selecting a recipes where the preptime is exactly 10 would look something like this:

Recipe.where(prep_time: 10)

Active Record Associations have also been covered now, too. Has many, belongs to, and has many through can connect your multiple databases in Rails.  It makes calling variables a bit more difficult, but Rails console is becoming essential to discovering the exact methods you can use. Creating multiple databases to store information more efficiently is essentially the main benefit for doing this.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s