Thursday, May 26, 2011

Build Your First Ruby on Rails App in Minutes!

Building your first app in Rails 3 is pretty simple and if you've got your git account, a heroku account and all the components installed and know your way around UNIX, you can have one up and running in just minutes.

Go to your terminal and enter the following:

rails new demo_app

You should get in return about 75 lines of text that look something like this:
      create 
      create  README
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/mailers
      create  app/models
      create  app/views/layouts/application.html.erb
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/backtrace_silencers.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/secret_token.rb
      create  config/initializers/session_store.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  config/database.yml
      create  db
      create  db/seeds.rb
      create  doc
      create  doc/README_FOR_APP
      create  lib
      create  lib/tasks
      create  lib/tasks/.gitkeep
      create  log
      create  log/server.log
      create  log/production.log
      create  log/development.log
      create  log/test.log
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/favicon.ico
      create  public/index.html
      create  public/robots.txt
      create  public/images
      create  public/images/rails.png
      create  public/stylesheets
      create  public/stylesheets/.gitkeep
      create  public/javascripts
      create  public/javascripts/application.js
      create  public/javascripts/controls.js
      create  public/javascripts/dragdrop.js
      create  public/javascripts/effects.js
      create  public/javascripts/prototype.js
      create  public/javascripts/rails.js
      create  script
      create  script/rails
      create  test
      create  test/fixtures
      create  test/functional
      create  test/integration
      create  test/performance/browsing_test.rb
      create  test/test_helper.rb
      create  test/unit
      create  tmp
      create  tmp/sessions
      create  tmp/sockets
      create  tmp/cache
      create  tmp/pids
      create  vendor/plugins
      create  vendor/plugins/.gitkeep

Move into the demo_app directory and run bundler.

cd demo_app
bundle

What you get in return should look something like this:
Fetching source index for http://rubygems.org/
Installing rake (0.9.0)
Using abstract (1.0.0)
Using activesupport (3.0.7)
Using builder (2.1.2)
Using i18n (0.5.0)
Using activemodel (3.0.7)
Using erubis (2.6.6)
Installing rack (1.2.3)
Using rack-mount (0.6.14)
Using rack-test (0.5.7)
Using tzinfo (0.3.27)
Using actionpack (3.0.7)
Using mime-types (1.16)
Using polyglot (0.3.1)
Using treetop (1.4.9)
Using mail (2.2.19)
Using actionmailer (3.0.7)
Installing arel (2.0.10)
Using activerecord (3.0.7)
Using activeresource (3.0.7)
Using bundler (1.0.10)
Using thor (0.14.6)
Using railties (3.0.7)
Using rails (3.0.7)
Using sqlite3 (1.3.3)
Your bundle is complete! It was installed into /Users/maryjenn/.rvm/gems/ruby-1.9.2-p0

Start your rails server using rails server . Then, open your browser to http://localhost:3000/. You should see the default Rails Welcome page. It looks like this:

Next, let's add your app to your git repository. Use ctrl + c to stop your server. Type the following in your terminal:
git init This initializes your git repository.
git add . This adds the app to your repository.
git commit -m "new app" This commits the app to your repository. The "-m" allows you to add a note about what is in the commit. This is especially useful when you are collaborating on a project with others and need to communicate what changes you made.

Next, let's get it on the web! We'll push it to Heroku. First, create a Heroku repository:

heroku create

You'll get a nice URL like this: http://falling-sky-128.heroku.com/. If you go to the URL, you'll see a sort of placeholder for your app, but you won't see what you see on your local server because we haven't added it yet. Let's do that.

git push heroku master

You should then see something that looks like this in your terminal:

Counting objects: 63, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (48/48), done.
Writing objects: 100% (63/63), 86.11 KiB, done.
Total 63 (delta 2), reused 0 (delta 0)

-----> Heroku receiving push
-----> Rails app detected
-----> Detected Rails is not set to serve static_assets
       Installing rails3_serve_static_assets... done
-----> Configure Rails 3 to disable x-sendfile
       Installing rails3_disable_x_sendfile... done
-----> Configure Rails to log to stdout
       Installing rails_log_stdout... done
-----> Gemfile detected, running Bundler version 1.0.7
       Unresolved dependencies detected; Installing...
       Using --without development:test
       Fetching source index for http://rubygems.org/
       Installing rake (0.9.0)
       Installing abstract (1.0.0)
       Installing activesupport (3.0.7)
       Installing builder (2.1.2)
       Installing i18n (0.5.0)
       Installing activemodel (3.0.7)
       Installing erubis (2.6.6)
       Installing rack (1.2.3)
       Installing rack-mount (0.6.14)
       Installing rack-test (0.5.7)
       Installing tzinfo (0.3.27)
       Installing actionpack (3.0.7)
       Installing mime-types (1.16)
       Installing polyglot (0.3.1)
       Installing treetop (1.4.9)
       Installing mail (2.2.19)
       Installing actionmailer (3.0.7)
       Installing arel (2.0.10)
       Installing activerecord (3.0.7)
       Installing activeresource (3.0.7)
       Using bundler (1.0.7)
       Installing thor (0.14.6)
       Installing railties (3.0.7)
       Installing rails (3.0.7)
       Installing sqlite3 (1.3.3) with native extensions
       Your bundle is complete! It was installed into ./.bundle/gems/
-----> Compiled slug size is 3.8MB
-----> Launching... done, v4
       http://flowing-river-673.heroku.com deployed to Heroku

To git@heroku.com:falling-sky-128.git
 * [new branch]      master -> master

Go to the URL Heroku created for you, and you should see your default Rails app! See? Easy!

Next, let's do some editing of the files rails generated to build some simple functionality into the app we created by creating a list. Let's do a song list--we'll list them by title and artist. We'll use Rails' scaffolding feature for this exercise, but in a professional context, it is not often used because it generates a lot of extra files that may or may not be used.

rails generate scaffold song title:string artist:string

In your terminal, you should see this:
         invoke  active_record
      create    db/migrate/20110525191620_create_songs.rb
      create    app/models/song.rb
      invoke    test_unit
      create      test/unit/song_test.rb
      create      test/fixtures/songs.yml
       route  resources :songs
      invoke  scaffold_controller
      create    app/controllers/songs_controller.rb
      invoke    erb
      create      app/views/songs
      create      app/views/songs/index.html.erb
      create      app/views/songs/edit.html.erb
      create      app/views/songs/show.html.erb
      create      app/views/songs/new.html.erb
      create      app/views/songs/_form.html.erb
      invoke    test_unit
      create      test/functional/songs_controller_test.rb
      invoke    helper
      create      app/helpers/songs_helper.rb
      invoke      test_unit
      create        test/unit/helpers/songs_helper_test.rb
      invoke  stylesheets
      create    public/stylesheets/scaffold.css

Let's do a migration: rake db:migrate

You'll see that rake has built a table for your songs!

(in /Users/maryjenn/src/demo_app)
==  CreateSongs: migrating ====================================================
-- create_table(:songs)
   -> 0.0018s
==  CreateSongs: migrated (0.0019s) ===========================================

Let's start the rails server again and go to localhost:3000 in your browser. You'll still see the rails default welcome page.

What? Why is that? Well, I'll talk about that in a minute and show you how to fix it, but add "/songs" to your URL. You should see a page with a header "Listing songs". Woohoo! We've actually built something! Now, play around with it. Notice there is a link to add new songs. C'mon, just add a couple.

Now, let's go look at the terminal. Notice that there is something going on under the hood, so to speak:

Parameters: {"utf8"=>"?", "authenticity_token"=>"oJP1EQL/KyGiswURylv9ySUVaWkjfwkAOge5GLI+8R0=", "song"=>{"title"=>"Go Do", "artist"=>"Jonsi"}, "commit"=>"Create Song"}
  [b]AREL (0.5ms) [/b] INSERT INTO "songs" ("title", "artist", "created_at", "updated_at") VALUES ('Go Do', 'Jonsi', '2011-05-26 15:19:40.314160', '2011-05-26 15:19:40.314160')

This is Active Record adding your entries to your app's data table. To me, Active Record is really where all the RoR magic happens. I'll get into Active Record in my next code sample, so be sure to check that one out. For now, let's change the routes so that the URL goes directly to our app, then deploy it to Heroku.

To redirect the URL, first go to /public/index.html and change name of that file to something like "old_index.html". If you don't do this, the browser will pick this up no matter what else you do. It's the default index page.

Then, go to /config/routes.rb and find the line that reads #root :to => "welcome#index". Uncomment it and change it to root :to => "songs#index". Save it.

Ctrl+C and Restart your server, then reload localhost:3000 in your browser. You should see your app, with the entries you have already made!

Now let's push it and deploy it.  
git add .
git commit -m "did migration and changed route" 
git push heroku master 
heroku rake db:migrate This adds your data table to your deployed app. Don't forget this!

Go check out your Heroku URL. Remember? The one that is similar to http://falling-sky-128.heroku.com/. Your app should be there with the same functionality as what you saw on localhost.

Congratulations! You've built your first rails app!

No comments:

Post a Comment