Homework for 7A

Review

Topics Covered: Coding databases and tables; Rails models; ActiveRecord; working with Rails models in rails console.


Exercises

E1: Checkpoint 1

Occasionally (usually once/week), we'll have you guys do a short checkpoint questionnaire so we can gauge how we're teaching the subject matter, and you yourself can gauge how well you're internalizing the concepts. They're designed to be a bit challenging, so please be careful in your answers.

Take the questionnaire

E2: ActiveReview

Again, we went over a lot of methods! Make sure you understand what each one returns, and whether they are a class or instance method. Look them up if you forgot—thankfully, Rails has really good documentation with APIDock.

What's the difference between .find and .find_by?
What's the difference between .where and .find_by?

Hover for answer

The first set of methods will be left for you to look up.

find takes one parameter, an integer, which is the ID of the resource. e.g. Tweet.find(1) gets the tweet with ID 1. find_by takes a hash, that has the parameter and a value, something like Tweet.find_by(:handle => "fizzcan").

.find_by returns just the first matching entry, whereas .where returns all matching entries.

E3: Tweeting like a Fiend

Fire up rails console from within your 'twitter' rails app folder from class today. Then do the following things. After you're confident in your code, write the commands you wrote for each step in d7/activerecord_commands:

  1. Create a User with a name and followers count
  2. Find it with User.find. Assign the result to the variable user
  3. Find it by name with User.find_by
  4. Write a command that finds all the users with followers count equal to 10.
  5. Update user from step 2 to have a different name. Make sure to save!
  6. Create a Tweet for this user. Assign the correct user_id, and make sure to save.
  7. Update the tweet from step 6 to have a different body.
  8. Destroy it.

A bit harder now:

  1. Create 10 users programmatically, each with a different name. Use a loop—you might want to write pseudo-code first!
  2. Destroy them all
  3. Create 10 tweets in a similar way.
  4. Update all of them to have the body "Ruby is fat"
  5. Update the fourth one to say "Ruby is getting even fatter"