Using Ruby Console for Rails Development
Jun 25
Lately I’ve been using the Ruby console to test my Rails models and application logic. It’s a very handy utility that I’ve only touched the surface of and wanted to post a simple example.
Let’s assume that you’ve created a test application with a model named Contacts. The contacts database has the basic structure:
id int primary key auto_increment
name varchar(100)
email varchar(100)
Be sure to configure your database.yml file to talk to your development database. Now you simply need to initialize the Ruby console by going into your Rails application directory and running the following command:
ruby script/console
You should see Loading development environment >> printed to the console. Now you can create an instance of a Contact object:
c = Contact.new
and you’ll see the object printed to the console:
#nil, “address_line1″=>nil, “name”=>nil, “postal_code”=>nil, “address_line2″=>nil, “country”=>nil, “phone”=>nil, “state”=>nil, “email”=>nil}, @new_record=true
Now let’s assign some properties to it:
c.name = “Dennis Baldwin”
c.email = “dennisbaldwin@gmail.com”
After each property assignment you’ll see the value echoed to the console. We can now write the new contact to the database by issuing the following command:
c.save
You should see true printed to the console meaning the new contact was saved successfully. This whole process can be simplified with the following command:
c = Contact.create(:name => “dennis baldwin”, :email => “dennisbaldwin@gmail.com”)
Pretty slick and all of this is made possible through the ActiveRecord class.
