The following blog post contains material either currently found or soon to be incorporated into my new book, "Easy Active Record for Rails Developers". Among many other topics, you'll learn about model generation, migrations, validations, associations, scopes, joins, includes, forms integration, nested forms, and model testing with RSpec and FactoryGirl. The book is now available, head over to this website's home page to learn more.
I find the Rails Console to be an indispensable tool, and leave a session open almost constantly throughout the day. It is supremely useful for easily and quickly experimenting with models, queries, and debugging various other data structures such as arrays and hashes. If you’re not familiar with the Rails console, you can enter a new console session by opening a terminal, navigating to your Rails project, and executing
rails console as demonstrated here:
$ rails console Loading development environment (Rails 4.0.0) 2.0.0p247 :001 >
Once you’ve entered the console you’re free to experiment with Ruby snippets, create new Active Record objects, or query those objects, among other things:
location = Location.new => #<Location id: nil, name: nil, description: nil, created_at: nil, updated_at: nil> 2.0.0p247 :002 > Location.count (4.3ms) SELECT COUNT(*) FROM `locations` => 0 2.0.0p247 :003 >
Because I spend so much time inside the console, I prefer to work with a streamlined prompt, and frankly have little use for the Ruby version or command number supplied within the default console prompt. Fortunately, the prompt is easily changed. You can choose to instead see a simplified console prompt consisting of just
>> by creating a file named
.irbrc and place it in your home directory. Inside it, add the following statement:
IRB.conf[:PROMPT_MODE] = :SIMPLE
After saving the file exit and re-enter the console and you’ll be treated to the simplified prompt! After saving the file, exit and enter the console anew to see the streamlined changes:
$ rails console Loading development environment (Rails 4.0.0) >>
While a minor change, reducing the amount of screen clutter gives you more opportunity to focus on what matters!
Like what you read? There’s plenty more where this came from in my new book, “Easy Active Record for Rails Developers”!