Jump to content

Photo

[Finished in a few hours] Ruby on Rails: A beginner's guide to your first webapp! (+Heroku)


  • Please log in to reply
16 replies to this topic

#1
Mo3

Mo3

    HTTP 420 Enhance Your Calm

  • Moderators
  • 2014 posts
  • Joined: 21-July 10
  • LocationBavaria
  • Expertise:PHP, Java, Javascript, Python, Ruby on Rails, Node.js, SQL, MongoDB

A beginner's guide to your first (simple) Ruby on Rails web application
Written by Mo3 - Last modified 3/12/2011


What's Ruby on Rails?

Ruby on Rails (http://rubyonrails.org/) is a object orientated, MVC-based web framework built on Ruby.

Ruby on Rails is mainly used for database powered webapps and has a notably higher development speed than other, comparable MVC frameworks due to its clearly defined structure and Ruby's easy syntax.

Step 1: Installing the oven

Download the latest version of Ruby:
http://www.ruby-lang.org/en/downloads

Open up the Ruby command line prompt (Windows) or Terminal (Linux) and enter the following commands:
gem install rails
gem install sqlite3

Done :)

Step 2: Getting to know some cooking basics

Before you get started, you should definitely visit tryruby.org and do the 15 minute tutorial - I'm serious, you'll want to have atleast a tiny bit of Ruby knowledge before we start.

Step 2: Preparing the ingredients

First we're going to create a new Rails application. To do so, enter

rails new mytestapp

This will create a new folder with Rails files inside. Let's switch to said folder..

cd mytestapp

We want our application to be database powered so we'll need to create a new SQLite database aswell -

rake db:create

This should successfully create a new database.

Time to check if Rails is working properly!

rails s

Open up your web browser and go to localhost:3000 - you should be greeted by a nice welcome message.

Step 4: The recipe

What we're going to create is something similar to 4chan - a text based forum without user system. We're NOT going to use scaffolding.

Step 5: Start cooking!

First we have to create a controller for the board. It needs to have the options "index" (To show the board's index) and "add" (To create a new post). Type this into your command line:

rails generate controller board index add

Rails then automatically generates all files (Views, helper and controlles).

Next up is a new model for posts. Models handle database queries for us. Our "post" model needs to have a few fields: One for the post text, one for the (self-assigned) user name and timestamp fields. To create said model, enter this:

rails generate model post text:string username:string --timestamps

The command above creates a new file called "randomnumber_create_posts.rb". It basically includes all the database stuff you usually need to do by yourself - create a new table and create all new fields.

To make Rake do exactly that, we have to execute this:

rake db:migrate

Done! :) Now it's time to fire up your favourite file editor. I'm using Komodo Edit.

First, delete "index.html" in the "public" directory - it's for the welcome message and we don't need it any more.

Then open up a file called "routes.rb" in the "config" directory. As the name already suggests, this is the file in which we can define all our routes in.

Right now routes.rb should look like this (If it doesn't, check if you completed all steps)

Mytestapp::Application.routes.draw do
  get "board/index"

  get "board/add"

  # The priority is based upon order of creation:
  # first created -> highest priority.

  # Sample of regular route:
  #   match 'products/:id' => 'catalog#view'
  # Keep in mind you can assign values other than :controller and :action

  # Sample of named route:
  #   match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
  # This route can be invoked with purchase_url(:id => product.id)

  # Sample resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Sample resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Sample resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Sample resource route with more complex sub-resources
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', :on => :collection
  #     end
  #   end

  # Sample resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end

  # You can have the root of your site routed with "root"
  # just remember to delete public/index.html.
  # root :to => "welcome#index"

  # See how all your routes lay out with "rake routes"

  # This is a legacy wild controller route that's not recommended for RESTful applications.
  # Note: This route will make all actions in every controller accessible via GET requests.
  # match ':controller(/:action(/:id(.:format)))'
end

We'll need exactly two route right now - the root path's route and another route for the add action. Let's create them..

Mytestapp::Application.routes.draw do
  root :to => "board#index"
  post "add" => "board#add"
end

"board#index" consists of "board" which is the name of our controller and "index", the action.

Next up we need to add a form to the index page which creates a new post.

Open up "index.html.erb" in "app/views/board". By default, that file should look something like this:

<h1>Board#index</h1>
<p>Find me in app/views/board/index.html.erb</p>

Delete the file's content and insert the following code:

<%= form_for :postinfo, @post, :url => { :action => "add" } do |f| %>
  <%= f.label :username %>
  <%= f.text_field :username %><br>
  <%= f.label :text %>
  <%= f.text_field :text %><br><br>
  <%= submit_tag "Post!" %>
<% end %>

This is going to create a form with one "username" and one "text" field and submit it to our board controller via HTTP POST.

But, wait! The controller doesn't know what to do with that data yet. Let's open up "app/controller/board_controller.rb" and tell it what to do.

class BoardController < ApplicationController
  def index
  end

  def add
    @post = Post.create(params[:postinfo])
    redirect_to root_path
  end
end

Post.create advises the model to create a new post in our database and use the information provided in params[:postinfo]. Then we redirect our user to the root path.

Let's test this out! Enter "rails s" in your console and visit localhost:3000 - a blank page should pop up with nothing but a form on it. Go ahead and create a new post :)

Then, enter "rails c" in your console. This starts up Rails' interactive command line. Enter

Post.all

to make Rails output every entry in our posts table. Your new post should be shown and look something like this:

irb(main):007:0> Post.all
=> [#<Post id: 1, text: "Why hello there!", username: "Mo3", created_at: "2011-03-12 18:00:41", updated_at: "2011-03-12 18:00:41">]

But, wait.. what if someone forgot to fill out all fields and submitted the form anyways? A blank entry would be made in our database - not the best thing to happen. But luckily we can prevent this by using Rails' integrated validation.

Open "app/models/post.rb", delete it's content and paste in the following:

class Post < ActiveRecord::Base
  validates :username, :presence => true
  validates :text, :presence => true
end

Node.js | Ruby on Rails | Python | PHP | Scala
What is necessary to change a person is to change his awareness of himself.


#2
TheEmpty

TheEmpty

    Chief of Staff

  • Members
  • 5278 posts
  • Joined: 02-October 10
  • Expertise:HTML, CSS, PHP, Java, Javascript, Python, Ruby on Rails, SQL
We Rick (iPod keeps correcting me.) web Rick is part if ruby, not rails. Also it's 'rake db:create' the db:migrate will only create a sqlite3 file, other databases will not work this way.
Unicode is awesome.
def ಥ╭╮ಥ {
  throw new Exception("Dev just gave up")
}

#3
Mo3

Mo3

    HTTP 420 Enhance Your Calm

  • Moderators
  • 2014 posts
  • Joined: 21-July 10
  • LocationBavaria
  • Expertise:PHP, Java, Javascript, Python, Ruby on Rails, Node.js, SQL, MongoDB

We Rick (iPod keeps correcting me.) web Rick is part if ruby, not rails. Also it's 'rake db:create' the db:migrate will only create a sqlite3 file, other databases will not work this way.


You may want to wait until the whole thing is finished, everyone makes mistakes :)

Node.js | Ruby on Rails | Python | PHP | Scala
What is necessary to change a person is to change his awareness of himself.


#4
TheEmpty

TheEmpty

    Chief of Staff

  • Members
  • 5278 posts
  • Joined: 02-October 10
  • Expertise:HTML, CSS, PHP, Java, Javascript, Python, Ruby on Rails, SQL

You may want to wait until the whole thing is finished, everyone makes mistakes :)

What if someone comes and reads it ;) wdr gets a lot of hits from Google.

edit: Hope you don't mind, I edited it up a bit to reflect that data, as well as some grammar errors.
Unicode is awesome.
def ಥ╭╮ಥ {
  throw new Exception("Dev just gave up")
}

#5
Mo3

Mo3

    HTTP 420 Enhance Your Calm

  • Moderators
  • 2014 posts
  • Joined: 21-July 10
  • LocationBavaria
  • Expertise:PHP, Java, Javascript, Python, Ruby on Rails, Node.js, SQL, MongoDB

What if someone comes and reads it ;) wdr gets a lot of hits from Google.

edit: Hope you don't mind, I edited it up a bit to reflect that data, as well as some grammar errors.


ABUSE

Nah it's okay, but I just overwrote your changes by accident coz I submitted a new edit D:

Node.js | Ruby on Rails | Python | PHP | Scala
What is necessary to change a person is to change his awareness of himself.


#6
TheEmpty

TheEmpty

    Chief of Staff

  • Members
  • 5278 posts
  • Joined: 02-October 10
  • Expertise:HTML, CSS, PHP, Java, Javascript, Python, Ruby on Rails, SQL
+1'd
I look forward to seeing the complete article :)
Unicode is awesome.
def ಥ╭╮ಥ {
  throw new Exception("Dev just gave up")
}

#7
TheEmpty

TheEmpty

    Chief of Staff

  • Members
  • 5278 posts
  • Joined: 02-October 10
  • Expertise:HTML, CSS, PHP, Java, Javascript, Python, Ruby on Rails, SQL
Dynamic form is no longer in rails. Removed in current version 3.0.5; they are slowly removing overheads and having people install them as plugins, which is great. Also going to move this to in progress. It's a great tutorial that I hope you finish and bring up to date :)
Unicode is awesome.
def ಥ╭╮ಥ {
  throw new Exception("Dev just gave up")
}

#8
derTechniker

derTechniker

    BadBoy™

  • Members
  • 1210 posts
  • Joined: 06-July 10
  • LocationAustria
  • Expertise:HTML, CSS, PHP, Javascript, SQL
This tutorial is pretty nice. For real beginners it would be better if you tell exactly what the things do.

Like

redirect_to root_path

... Yeah i know, we can read that and know it redirects to the root path. But where else can we redirect the user when using "rediret_to" ?


I know it's not finished. But just to let you know this might be something people want to know.

#9
TheEmpty

TheEmpty

    Chief of Staff

  • Members
  • 5278 posts
  • Joined: 02-October 10
  • Expertise:HTML, CSS, PHP, Java, Javascript, Python, Ruby on Rails, SQL
Because I'm not sure if mo3 knows this and I can't sleep.

redirect_to root_path

... Yeah i know, we can read that and know it redirects to the root path. But where else can we redirect the user when using "rediret_to" ?


redirect_to() takes one argument, either a hash or a string. A hash would be the controller/action and parameters eg: {:action => 'some_action'} is current controller#some_action or {:controller => 'home', :action => 'index', :ref => request.request_uri} would go to home#index with ?ref=(address)

or a string such as "http://google.com" or "/home/index". root_path, if I remember correctly, will return a hash, while root_url will return a string.
Unicode is awesome.
def ಥ╭╮ಥ {
  throw new Exception("Dev just gave up")
}

#10
derTechniker

derTechniker

    BadBoy™

  • Members
  • 1210 posts
  • Joined: 06-July 10
  • LocationAustria
  • Expertise:HTML, CSS, PHP, Javascript, SQL

Because I'm not sure if mo3 knows this and I can't sleep.



redirect_to() takes one argument, either a hash or a string. A hash would be the controller/action and parameters eg: {:action => 'some_action'} is current controller#some_action or {:controller => 'home', :action => 'index', :ref => request.request_uri} would go to home#index with ?ref=(address)

or a string such as "http://google.com" or "/home/index". root_path, if I remember correctly, will return a hash, while root_url will return a string.


Nice thanks.

It seems this tutorial is one of those who never get finished. So theEmpty, would you be so kind to write down a nicely tutorial with also telling us how to do the testing and stuff with rails?

#11
Mo3

Mo3

    HTTP 420 Enhance Your Calm

  • Moderators
  • 2014 posts
  • Joined: 21-July 10
  • LocationBavaria
  • Expertise:PHP, Java, Javascript, Python, Ruby on Rails, Node.js, SQL, MongoDB
My parents are getting divorced right now. I don't have the time.

(And FYI, there's a never finished tutorial by Empty too)

Node.js | Ruby on Rails | Python | PHP | Scala
What is necessary to change a person is to change his awareness of himself.


#12
derTechniker

derTechniker

    BadBoy™

  • Members
  • 1210 posts
  • Joined: 06-July 10
  • LocationAustria
  • Expertise:HTML, CSS, PHP, Javascript, SQL

My parents are getting divorced right now. I don't have the time.

(And FYI, there's a never finished tutorial by Empty too)



Bad think, i'm sorry but i did not know this ;-)

Yeah i know. Not only you and theEmpty. there are more tutorials of that kind.

#13
Mo3

Mo3

    HTTP 420 Enhance Your Calm

  • Moderators
  • 2014 posts
  • Joined: 21-July 10
  • LocationBavaria
  • Expertise:PHP, Java, Javascript, Python, Ruby on Rails, Node.js, SQL, MongoDB
Going to finish this today or tomorrow.

Node.js | Ruby on Rails | Python | PHP | Scala
What is necessary to change a person is to change his awareness of himself.


#14
TheEmpty

TheEmpty

    Chief of Staff

  • Members
  • 5278 posts
  • Joined: 02-October 10
  • Expertise:HTML, CSS, PHP, Java, Javascript, Python, Ruby on Rails, SQL

Going to finish this today or tomorrow.

Greatly look forward to it :)
Unicode is awesome.
def ಥ╭╮ಥ {
  throw new Exception("Dev just gave up")
}

#15
TheEmpty

TheEmpty

    Chief of Staff

  • Members
  • 5278 posts
  • Joined: 02-October 10
  • Expertise:HTML, CSS, PHP, Java, Javascript, Python, Ruby on Rails, SQL
out of date now XD form_for and routes (routes in 3.1)
Unicode is awesome.
def ಥ╭╮ಥ {
  throw new Exception("Dev just gave up")
}

#16
Mo3

Mo3

    HTTP 420 Enhance Your Calm

  • Moderators
  • 2014 posts
  • Joined: 21-July 10
  • LocationBavaria
  • Expertise:PHP, Java, Javascript, Python, Ruby on Rails, Node.js, SQL, MongoDB

out of date now XD form_for and routes (routes in 3.1)


3.1 is still Beta..

Anyway, I hope I can find some time to finish this next week.

Node.js | Ruby on Rails | Python | PHP | Scala
What is necessary to change a person is to change his awareness of himself.


#17
TheEmpty

TheEmpty

    Chief of Staff

  • Members
  • 5278 posts
  • Joined: 02-October 10
  • Expertise:HTML, CSS, PHP, Java, Javascript, Python, Ruby on Rails, SQL

3.1 is still Beta..

Anyway, I hope I can find some time to finish this next week.

form_for was outdated back in 3.0.5 or 3.0.7 also 3.1 comes out this week if I remember correctly. (so today or tomorrow)
Unicode is awesome.
def ಥ╭╮ಥ {
  throw new Exception("Dev just gave up")
}




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users