Building Web Applications with Ruby on Rails

Steven Petryk

Rails vs WAMP

  • Convention over configuration
  • Database-agnostic
  • Automatic SQL sanitation
  • Integrated webapp security
  • Incredibly active community
  • Separation of concerns

Rails :)

WAMP :(

  • Requires much configuration
  • Depends on MySQL
  • SQL is written by hand
  • No inherent security features
  • Uses PHP :'(

The MVC Paradigm

  • Models
    • Persisted in the database
    • Responsible for abstracting database operations
  • Views
    • Display models
    • Present ways to interact with models
  • Controllers
    • Tie together models and views
    • Render views and perform actions on models based on user action

Models in Rails

  • Powered by ActiveRecord
    • ORM – tries to eliminate SQL by exposing Ruby methods on a Model object
    • Automatically manages conversion from database columns to Ruby types
    • Provides extremely intelligent ways to query, parse, and store data
    • Allows you to easily validate models
    • ... much more.

ActiveRecord in Action

$ rails generate model task name done:boolean due_at:datetime

1. Create the task model

# Create a task
task = Task.create(name: "Give Rails Tech Talk", due_at: Time.now)
task.name # => "Give Rails Tech Talk"

# Find and update a task
Task.find_by_name("Give Rails Tech Talk").update(done: true)

# Get a Relation of tasks
urgent_tasks = Task.where(done: false).where('due_at < ?', 1.day.from_now)

# Destroy a task
Task.last.destroy
$ rake db:migrate

2. Migrate the database

3. ????    4. Profit

ActiveRecord Demo

Creating a Task model

Controllers and Views

  • Manipulate models and expose interfaces for reading and modifying their attributes
  • ActionController: the Rails controller class
    • Parses parameters
    • Enables filtering of model attributes for security
    • Automatic mapping of exceptions to HTTP status codes
    • ... much more.

ActionController in Action

rails generate controller tasks index new create show edit update destroy

1. Create the TasksController

class TasksController < ApplicationController
  def index
  end

  def new
  end

  def create
  end

  def show
  end

  def edit
  end

  def update
  end

  def destroy
  end
end

2. Update your routes    3. ???     4. Profit

ActionView

  • Powerful template system
  • Encourages separation of logic and view
  • Has helper methods for working with dates, linking to models, and generating forms.

Demo

The rest of the app

Where to learn more

  • Mike Hartl's Ruby on Rails Tutorial (free)
    http://​ruby.railstutorial.org/book
     
  • Ryan Bates' "Railscasts" screencasts
    http://railscasts.com
     
  • Ruby on Rails' actual website
    http://rubyonrails.org
     
  • The Rails 4 Way (not free, for advanced users)

We will be learning Rails in depth in SIGWEB.

Sundays from 4:30-6:15.

Student Union 220.

Rails Intro

By Steven Petryk

Rails Intro

  • 307

More from Steven Petryk