My first app using Ruby on Rails on Mac OS X Lion: here we go!
MVC: what’s that?
Now that we have successfully installed and tested Ruby on Rails (hopefully), now it’s time to set up your first database driven application. (For this tutorial I am using Sqlite3 for the database, so I have skipped modifying the ../db/database.yml file). With this tutorial, will will use the scaffolding option, as it gives us a basic structure to start building and customizing a new app. Once you get more familiar with RoR you can start creating apps from scratch, perhaps even using your own templates. (Similar to the way train rails are built buy first using scaffolding, later on in construction you add steel, let the concrete dry, decorate it…). By the way, RoR uses MVC (Models, Views, Controllers). Don’t worry about it, it sounds confusing but its really quite simple, this diagram helps put it into context:
As you can see, the web pages aren’t involved in maintaining business rules or managing logic, that’s all left to the model, the controller is like the crazy glue for the models/db and the web pages.
Let’s get started
So, let’s start by creating your RoR application directory:
$ rails new myFriends
This command will create your basic folder structure with a bunch of files.
Now cd into your new myFriends folder and start the rails server.
$ cd myFriends
$ rails server
This will bring you to the point where you may test to see if it’s working by navigating to http://localhost:3000 with your favorite web browser. You should see a Welcome aboard message in your browser.
If it’s not working, make sure that your Ruby version is set to 1.9.2, the system default of 1.8.7 has some issues with the later version of rails:
$ rvm 1.9.2
Build a skeleton app with some scaffolding
Now we are ready to use scaffolding to add the basic MVC framework.
$ rails generate scaffold post firstName:string lastName:string address:text dob:date sex:text relationship:text
After entering this command, more files will be created within your existing RoR folder structure.
This command creates a CRUD interface (Create, Read, Update, Delete) using the post model for your myFriends application. In other words, it creates the basic MVC (Model, View, Controller) structure automatically. (We’ll get into *.rb, *.erb and *.yml files in another post). Check out that a scaffold.css file has been created which will allow you to customize the look and feel within your web pages.
By the way, you may see all MVC files in the app directory of your application, it’s a good time to start getting familiar with this file structure. If you cd into myFriends/app, you will see models, views, and controllers directories.
It also creates a migration file <utctimestamp_create_posts.rb> in your ../db/migrate folder, which should have content similar to:
class CreatePosts < ActiveRecord::Migration
def self.up
create_table :posts do |t|
t.string :firstName
t.string :lastName
t.text :address
t.date :dob
t.text :sex
t.text :relationship
t.timestamps
end
end
def self.down
drop_table :posts
end
end
Time to create a database
Now we can create your new application database with the following command:
$ rake db:create
As mentioned, a database migration file is a timestamped file with methods to create, populate, delete…etc database tables and columns. This is a super handy feature, as it lets you use the rake db:migrate command to update your database or roll it back to previous versions. Better yet, you can migrate to new database versions in your development environment without affecting your testing o production environments.
If you navigate to http://localhost:3000/posts/new you’ll see that the relationship and sex fields are text. Yuck!! What to do? Well, let’s update the database data types and then update the web form to fix it.
Let’s start by creating a new database migration file:
$ rails generate migration myFriends_sex_relationship_migration
You’ll see a new file in your ../db/migration folder similar to 20110801001604_my_friends_sex_relationship_migration.rb. Ok, now all we have to do is modify the file (it has no methods by default) so that it changes sex and relationship columns in the posts table with the new data types:
class MyFriendsSexRelationshipMigration < ActiveRecord::Migration
def self.up
change_column :posts, :sex, :string
change_column :posts, :relationship, :string
end
def self.down
change_column :posts, :sex, :text
change_column :posts, :relationship, :text
end
end
self.up is the new stuff, self.down is the old stuff.
Now migrate to the new database.
$ rake db:migrate
Customize your Form
Now you need to update your web site form so that the form also reflects this new datatype. Edit the ../app/views/posts/_form.html.erb and change the sex and relationship fields from:
<%= f.text_area :sex %> and <%= f.text_area :relationship %>
to
<%= f.text_field :sex %> and <%= f.text_field :relationship %>
which changes the sex and relationship fields from text area to text fields, respectively. You can also change some of the labels and title page by modifying ../app/views/posts/index.html.erb file. (Files with *.erb files are files with Ruby code that may be embedded into HTML files).
You can also add some validation if you want, by modifying the ../app/models/posts.rb file:
class Post < ActiveRecord::Base
validates :firstName, :presence => true
validates :lastName, :presence => true
validates :sex, :presence => true,
:length => { :minimum => 4 }
end
This will make sure that the First Name, Last Name and Sex fields have been filled and that the Sex field has a minimum of four characters. Here’s what the form would look like if you tried to add “M” instead of “Male”:
Although you don’t really need to, restart server using Ctrl +C, retype rails server and go to http://localhost:3000/posts/new. Your new posts page now should look a little more sane:
Just to make sure, create a new post entry with data from your new friend (in this case it’s my nephew). If all goes well, you should get a confirmation page telling you that the post was created successfully:
Getting rid of Welcome aboard smoke test: changing the index page
Notice how we still aren’t pointing to the myFriends application within the root of the URL, we are getting there by navigating to the ../posts virtual directory. Let’s change that so that the Welcome aboard page is substituted with your own index page.
First, we need to create a home page for the myFriends application. As usual, RoR provides a handy way to do that:
$ rails generate controller home index
As you can see, this command creates a home controller (app/controllers/home_controller.rb) with views in the ../app/views/home directory. Open the ../app/views/home/index.html.erb file and modify it so that it looks something like:
<h1>Greg’s Friends and Family</h1> <%= link_to “View my friends and family”, posts_path %> <%= link_to “New Friends”, new_post_path %>
This code adds page title and add labels along with links to the posts_path and new_posts_path methods of your application. The first one is so everyone can see my friends (no privacy controls here) and so that anyone can add themselves to the list.
Ok so we’ve added a new home controller with some views and modified the home index view a little, now it’s time to substitute the Welcome aboard RoR default page with our own. By default, the Welcome aboard page is in the ../public folder, so let’s get rid of it:
$ rm public/index.html
Now we have to modify the ../config/routes.rb file. The routes.rb dictates how to connect incoming requests to controllers and actions. Uncomment:
root :to => “welcome#index”
line and change it to:
root :to => “home#index”
Save and go to http://localhost:3000. Hopefully, you have something similar to:
Time to celebrate
Congrats!! Now you have your skeleton app to organize your friends and family. Watch out Facebook!!!











