41. Action HTTP Method URL XML
index GET /jobs /jobs.xml
show GET /jobs/1 /jobs/1.xml
new GET /jobs/new
edit GET /jobs/1;edit
create POST /jobs /jobs.xml
update PUT /jobs/1 /jobs/1.xml
destroy DELETE /jobs/1 /jobs/1.xml
84. # GET /employers
# GET /employers.xml
def index
@employers = Employer.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @employers }
end
end
app/controllers/employers_controller.rb
85. # GET /employers
# GET /employers.xml
def index
@employers = Employer.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @employers }
end
end
app/controllers/employers_controller.rb
86. # GET /employers
# GET /employers.xml
def index
@employers = Employer.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml =>
@employers }
end
end
app/controllers/employers_controller.rb
92. # GET /employers/new
# GET /employers/new.xml
def new
@employer = Employer.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @employer }
end
end
app/controllers/employers_controller.rb
94. # POST /employers
# POST /employers.xml
def create
@employer = Employer.new(params[:employer])
respond_to do |format|
if @employer.save
flash[:notice] = 'Employer was successfully created.'
format.html { redirect_to(@employer) }
format.xml { render :xml => @employer,
:status => :created, :location => @employer }
else
format.html { render :action => quot;newquot; }
format.xml { render :xml => @employer.errors, :status
=> :unprocessable_entity }
end
end
end
app/controllers/employers_controller.rb
95. # GET /employers/1
# GET /employers/1.xml
def show
@employer = Employer.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @employer }
end
end
app/controllers/employers_controller.rb
115. class CreateJobs < ActiveRecord::Migration
def self.up
create_table :jobs do |t|
t.integer :employer_id
t.string :name
t.text :description
t.timestamps
end
end
def self.down
drop_table :jobs
end
end
db/migrations/2009...create_jobs.rb
118. jobs employers
Model: Job Model: Employer
belongs_to :employer has_many :jobs
id integer id integer
employer_id integer name string
name string address string
119. employers jobs
Model: Employer Model: Job
has_one :job belongs_to :employer
id integer id integer
name string employer_id integer
address string name string
120. employers jobs
Model: Employer Model: Job
has_many :jobs belongs_to :employer
id integer id integer
name string employer_id integer
address string name string
121. physicians
Model: Physician
has_many :appointments
has_many :patients,
:through => :appointments
appointments
id integer
Model: Appointment
name string belongs_to :physician
belongs_to :patient
id integer
patients
physician_id integer
Model: Patient
patient_id integer
has_many :appointments
has_many :physicians,
:through => :appointments
id integer
name string
133. # GET /jobs
# GET /jobs.xml
def index
@jobs = @employer.jobs
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @jobs }
end
end
app/controllers/jobs_controller.rb
134.
135. # GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
@job = @employer.jobs.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
app/controllers/jobs_controller.rb
138. # POST /jobs
# POST /jobs.xml
def create
@employer = Employer.find(params[:employer_id])
@job = @employer.jobs.build(params[:job])
respond_to do |format|
if @job.save
flash[:notice] = 'Job was successfully created.'
format.html { redirect_to employer_job_url(@employer, @job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => quot;newquot; }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
app/controllers/jobs_controller.rb
139. # GET /jobs/1
# GET /jobs/1.xml
def show
@job = @employer.jobs.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @job }
end
end
app/controllers/jobs_controller.rb
I’ll be graduating with an MBA from Crummer in August.
Certified ScrumMaster
I’m the CEO of ADS, a web development shop in Orlando
We develop an online suite of apps
Scrum’d: simple project management for agile teams
Expens’d: simple expense tracking
Prioritiz’d: all about getting things done
Find me on Twitter
My wife and daughter are here in Las Vegas
Two quick movies I want to share
A few people commented on our blog
I can provide specific help after the tutorial
Ruby
Created by Yukihiro “matz” Matsumoto
1995 - public release
2006 - gained mass acceptance
Blending of languages: Perl, Smalltalk, Eiffel, Ada, and Lisp
Ranked #10 in the world on the Tiobe index, April 2009
Open source
Everything is an object
Everything can be given it’s own properties (instance variables) and actions (methods)
All types have methods and instance variables
The same rules apply everywhere
Ruby is Flexible
Freely alter Ruby’s parts
Remove, redefine, and extend at will
Ruby is Easy on the Eyes and Brain
Very limited punctuation
Preference for English keywords
Enhanced readability and reduced learning curve
Created by David Heinemeier Hansson
Extracted from Basecamp - 37signals
Released to the public
Full-stack framework for developing database-backed web applications
Uses the Model-View-Controller pattern
Builds on the power of Ruby
Stresses convention over configuration
Productivity gains: smaller teams, faster time to market, more concurrent projects
Code management: less code = easier management
Faster development
Simpler solution for a common problem: web-front end to a database
Data warehousing and data mining
Statistics reporting
Management systems
Collaborative applications
Community sites
E-commerce applications
Content management systems
Open source
A model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, one table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models.
Views represent the user interface of your application. In Rails, views are often HTML files with embedded Ruby code that performs tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application.
Controllers provide the “glue” between models and views. In Rails, controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.
One route in our app
REST
Maps actions to HTTP methods
In the course of building this app I will explain the basics:
Directory structure
Migrations
Models, views, controllers
Routes
More
Generate a Rails app with the Postgres database
Generate a Rails app with the MySQL database
Rails directory structure
This is a brief instruction manual for your application.
Use it to tell others what your application does, how to set it up, and so on.
On GitHub, many devs use this as the home page
This file contains batch jobs that can be run from the terminal.
Contains the controllers, models, and views for your application.
You’ll focus on this folder for the remainder of this tutorial.
Looking into the app directory, where lot’s of our code goes
Configure your application’s runtime rules, routes, database, and more.
Shows your current database schema, as well as the database migrations.
In-depth documentation for your application.
Extended modules for your application (more advanced than we’ll go today)
Application log files.
The only folder seen to the world as-is. This is where your images, javascript, stylesheets (CSS), and other static files go.
Scripts provided by Rails to do recurring tasks, such as benchmarking, plugin installation, and starting the console or the web server.
Unit tests, fixtures, and other test apparatus.
Temporary files
Third-party code.
Gems, plugins, Rails, etc.
Configure the database - Postgres
Configure the database - MySQL
Create the database
Fire up the server
Starts our application in development mode (by default)
Can start the local server in development, testing, or production
* Highly suggest running in production mode for testing OR set up a staging server
Browse to http://localhost:3000
Should see something like this
The default Rails page, located at public/index.html
Remove the public index file
The basic way to create the employer model
Use scaffolding to create an Employer
- Typically you’d get rid of this later
- You’ll need to customize what has been generated
- The better you get, the less scaffold you’ll use
Directories and files created with the generator
The biggies
The table and fields are created when we run this
Run the migration
Since we’re in development, it will be applied to the dev database
Create the default root
We’ll use this later
Uncomment the line in routes.rb and change it
The list page
Create two employers
Update one
Delete one
Our employer model
Our employer model
Add validations: these are two of many
Employer errors
Skinny controller fat model
Jamis Buck - Rails core team member
The controller has the CRUD, and that’s it
Put all logic into the model, not into the controller
Result: better code reuse, keep details in templates, easier testing
The console is a tool that gives us the runtime environment at a command-line
Use it for testing, rather than trying everything in a browser
Can fully interact with a database
Can run in any Rails environment: development, testing, production
Fire it up
Create new objects
Save objects
View errors
Use “reload!” to see updates to your models
We first pull up a list of employers using the index action
Above the action is the REST call
We can have numerous return formats: html, xml, json
Above the action is the REST call
Data return formats
We can have numerous return formats: html, xml, json
Index view
h is a Rails helper method to sanitize displayed data, preventing cross-site scripting attacks
link_to builds a hyperlink to a particular destination
edit_employer_path is a helper that Rails provides as part of RESTful routing.
You’ll see a variety of these helpers for the different actions that the controller includes.
Employer layout
<%= yield %> is where views get rendered into
The scaffold generator creates a default layout for each model
We can create a master layout that is applied to all, and either have a per-model layout, or remove them
First, create a new employer first by showing the new form
Instantiate a new employer
New view
Form helpers
error messages, label, text field, submit
The employer is then created by the create action
Next we show the employer
This shows only a single employer
Show view
If we want to edit the employer we retrieve the employer using the edit action
Edit view
The update action actually updates the record
The destroy action will remove the employer from the database
The new and edit forms have the same form fields
Name the partial
In the same view folder as all the other employer stuff
The “_” indicates it’s a partial
The new partial
Render the partial
Can render partials that are in any folder
Can render partials that are in any folder by specifying the folder and the partial name
Duplicates in the show, edit, update, and delete methods
Put it all into a before filter
Before filters run before actions
After filters run after actions
Put this code underneath the controller declaration
The code for the before_filter
Put it at the bottom of the controller above the last end
Use scaffolding to create a Job
Created our model, our views, and our controller
Job migration
Run the migration
Model relationships
Belongs_to association
One-to-one connection
Each job can be assigned to only one employer
Has_one association
One-to-one connection
* Used if an employer had one and only one job
Has_many association
The other side of the belongs_to association
One-to-many connection
Each instance of employer has 0 or more jobs
Has_many through association
Many-to-many connection
The third model sets up the association
Has_and_belongs_to_many association
Many-to-many connection
Our job model
Our job model
Our job model
Our updated employer model with the connection to the jobs
Create jobs as a nested resource within employers
Just like with the Employer controller, create a before filter on the Jobs controller
The code for the before_filter
Put it at the bottom of the controller above the last end
Index action to create a job
Index view
Create a new job as a resource of an Employer
This creates a new Job object and sets up the employer_id field to have the id from the specified Employer object in a single operation
New view
Create action
Show the job
Show view
If we want to edit the job we retrieve the job using the edit action
Edit view
The update action actually updates the record
The destroy action will remove the job from the database
Hook the employer and it’s jobs together
Update the show view for employers
Each employer has it’s own jobs collection
Now we can see the employer and get to their jobs
And we can see the list of jobs for the employer, and CRUD them.
Add a simple search form to our index page
Simple employer search
Search form added to employers/index.html.erb
Update the index method
Keep the search in the box
Updated search form
Shows our query in the search box
Updated index action
@query allows us to capture information and use it in a form