Read my latest article: 8 things I look for in a Ruby on Rails app (posted Thu, 06 Jul 2017 17:59:00 GMT)

Are you a console master?

Posted by Fri, 19 Aug 2005 03:06:00 GMT

1 comment Latest by Lance Wed, 02 Aug 2006 11:58:30 GMT

I have a few questions.

1.) Do you know what ./script/console does?

2.) If not, why not?

3.) If so, do you have any fun tips and tricks to share with the masses?

It occured to me earlier that many people, who might have came from the PHP camp, may have never really tested their object-oriented code from some sort of interactive program. (irb) If you are coming from the Python, Java, etc worlds, interactive testing isn’t anything new. Rails is nice enough to bundle a console script right within it!

I meet people online who have never even tried to run it. There are not many tutorials on the wiki that show console… and in my opinion, its one of the coolest things about Ruby and Rails. (but, I come from the php world…)

So, if you aren’t using it… why not? got a moment? try this from the root path of your Rails application.

./script/console
It start up okay? If so, what is the name of one of your models? Let’s say that I have a model structure like:
class Customer < ActiveRecord::Base
  has_many :orders, :dependent => true
end

class Order < ActiveRecord::Base
  belongs_to :customer
end
From console, you can access your models and do all sorts of fun things.
>> y = Customer.find(16)
=> #<Customer:0x2743ea4 @attributes={"name"=>"Robby", "id"=>"16"}>
>> y.orders
=> [#<Order:0x27416b8 @attributes={"id"=>"18", "amount"=>"12.00", "customer_id"=>"16"}>, #<Order:0x274167c @attributes={"id"=>"19", "amount"=>"12.50", "customer_id"=>"16"}>] 

Pretty neat, huh?

>> o = Order.find(18)
=> #<Order:0x273da68 @attributes={"id"=>"18", "amount"=>"12.00", "customer_id"=>"16"}>
>> o.customer.name
=> "Robby" 

If you are remotely a console wizard, please share some tips and tricks for those who are not sure what to do with it. I personally find myself in console all the time that I am working with Rails, testing stuff out with my models, before I move any of the code to my application.

It sure beats, hitting refresh in your browser all day. :-)

Get help with your Rails project

comments powered by Disqus
Comments
  1. Avatar
    Lance Wed, 02 Aug 2006 11:58:30 GMT

    Hi Robby,

    Like yourself, I am happy to use the console a lot. I was wondering if there is anyway to get your model objects to list only the methods that you have added and also their relationships with other model objects. For instance to get your author object to list its associated books etc.

    Thanks a lot, and keep up the good work. Look forward to seeing your patch to help rails use postgres int[] arrays make it into core.