Ruby On Rails: utilities and console commands

run rails as in prod mode (in your dev env)

$ bundle exec rake assets:precompile
$ bundle exec rake db:migrate RAILS_ENV=production

change this line inside: config/environments/production.rb

  config.serve_static_files = true

run your server as:

SECRET_KEY_BASE=`rake secret` rails s -e production -b 0.0.0.0

the -b part is only if you are running inside vagrant and port forwarding.

console

$heroku console # brings the console in the production site if hosted in heroku…. amazingly easy to access prod!

$ rails console –sandbox
This starts the console, and rollback any changes we make to the data once we exit the console

$ rails console test
Loads the test environment in the console (instead of the default development environment)

$ tail -f log/development.log
Tailing the development log

Basic console commands:

>> User.column_names # Describe the model’s attributes (or db column names)
>> User.new # Creates a new user object
>> user = User.new(:name => “Michael Hartl”, :email => “mhartl@example.com”) => # >> user.save # Save the object specified
>> user.name # access a specific property of the object
>> User.create(:name => “A Nother”, :email => “another@example.org”) # same as a user.New and a user.save
>> foo.destroy # destroy a created object, but the created object will still in memory (see below)
>> foo => # #Still gave you something even after destroy

>> User.find(1) # Find user with id 1
>> User.find_by_email(“mhartl@example.com”) # Find user by email (or any other specific attributes)
>> User.first # Find the first user in DB
>> User.all # Returns all usrs

>> user.email = “mhartl@example.net” #Updating a user’s property, and then do user.save
>> user.update_attributes(:name => “The Dude”, :email => “dude@abides.org”) #Update several attr at once, and also performs a user.save at the end, only attributes indicated on the object as attr_accessible can be updated this way

>> user.errors.full_messages # If there were errors when saving the data, they will be contained here

If you want to access some of your helper methods while in the console:

>include ActionView::Helpers::TextHelper  // Now you can use them

You can also use raw sql statements to interact with your database, by loading an sql console the following way:

rails dbconsole

One thought on “Ruby On Rails: utilities and console commands”

Leave a Reply

Your email address will not be published. Required fields are marked *