Rails Lesson #2: The Console
14 Apr 2008
In Lesson #1 We had a cookbook and a recipe but they weren't related to each other. First we'll add a key to the recipes table then we'll use the console to relate the entities.
When creating new objects we use the script/generate scaffold command. Here we only want to change the existing recipes table so we generate a migration:
$ script/generate migration add_cookbook_id_to_recipes
This will create a file in the db/migrate folder called 003_add_cookbook_id_to_recipes.rb
Open this file using your editor of choice and add the add_column and remove_column lines so that your file looks like the code below:
class AddCookBookIdToRecipes < ActiveRecord::Migration def self.up add_column :recipes, :cookbook_id, :integer end def self.down remove_column :recipes, :cookbook_id end endNow rake the migration:
$ rake db:migrateNow that we have a foreign key in the table we need to tell the CookBook model that it has many Recipes and the Recipe model that it belongs to a CookBook. So we open the model files in the app/model directory and add the lines shown below.
class Cookbook < ActiveRecord::Base has_many :recipes end
class Recipe < ActiveRecord::Base belongs_to :cookbook endNow the models are all wired up and ready for action. Let's start by associating the recipe record we created with the cookbook record. We could access the database and populate the field but it's a lot more fun to use the rails console. Go back to your terminal window and type:
$ ruby script/console Loading development environment (Rails 2.0.2) >> []What is now staring you in the face is called the rails console which is a special version of the IRB (Interactive Ruby Prompt.) This prompt will accept any valid ruby code. Go ahead and write a hello world command:
Loading development environment (Rails 2.0.2) >> puts "hello world" hello world => nil >> []
Try typing these commands just for fun:
>> 50.times { |n| puts "ruby is #{n} times better!" } >> 6+49 >> 5*5
The IRB is cool but what is special about the rails console is that it loads all your code and makes your models (and everything else) accessible for you to play with. So let’s take a look at what is in the database.
>> CookBook.find(:all) => [ an array containing any cookbooks you've created ] >> Recipe.find(:all) => [ an array containing any recipes you've created ]
Assuming you only have one cookbook and one recipe we can use the following commands to retrieve the recipe from the database and store it in the variable r, then fetch the cookbook into variable c, and finally tell r that it belongs to c:
>> r = Recipe.find(1) >> c = CookBook.find(1) >> r.cookbook = c >> r.save
The console is a very cool tool for quickly manually testing things or nudging data this way or that.