rails basics Tuesday, May 28, 13
rails basics
Tuesday, May 28, 13
how do browsers work?
Tuesday, May 28, 13
what does rails do?
Tuesday, May 28, 13
MODELS, Views, Controllers
rMVC
(and routes)
Tuesday, May 28, 13
router
Tuesday, May 28, 13
Tuesday, May 28, 13
Tuesday, May 28, 13
ROUTER
the router looks at the incoming request and sends it to the right controller.
Example:
myapp.com/users/1/edit
goes to the users controller, edit action(and sends a ‘parameter’ for user_id=1 as )
Tuesday, May 28, 13
ROUTER
/users users#index list all users
/users/1 users#show show user with id 1
/users/new users#new make a new user
/users/1/edit users#edit edit user with id 1
Tuesday, May 28, 13
SAMPLE ROUTE
RedditDemo::Application.routes.draw do match 'users/' => 'users#index' root to: 'users#index'end
Tuesday, May 28, 13
controller
Tuesday, May 28, 13
Tuesday, May 28, 13
CONTROLLER
The controller orchestrates the request.
It communicates with models to gather and manipulate data.
It then passes that data to the view.
Tuesday, May 28, 13
CONTROLLER ACTIONS
Controllers have multiple actions.
The standard ‘restful’ actions are:
indexshowcreateneweditupdatedestroy
Tuesday, May 28, 13
SAMPLE CONTROLLER
class UsersController < ActionController::Base def index @users = User.all endend
Tuesday, May 28, 13
models
Tuesday, May 28, 13
Tuesday, May 28, 13
MODELS
Models represent the nouns and data in your application.
They make sure stored data is valid, and perform calculations/analysis.
Tuesday, May 28, 13
DATABASES
•Store our model data (in rows), and define the attributes (columns).
•We manage changes in our database with migrations.
Tuesday, May 28, 13
MIGRATION
>> rails generate migration CreateUsers
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :netid
t.timestamps
end
end
end
Tuesday, May 28, 13
DATABASE
id first_name last_name netid
1
2
3
Adam Bray alb64
Vladimir The Bear vtb39
Charlie The Horse cth44
users
Tuesday, May 28, 13
DATABASE
id first_name last_name netid
1
2
3
Adam Bray alb64
Vladimir The Bear vtb39
Charlie The Horse cth44
users
Tuesday, May 28, 13
ADDING ANOTHER COLUMN
rails generate migration AddClassYearToUsers class_year:integer
Tuesday, May 28, 13
DATABASE
id first_name last_name netid class_year
1
2
3
Adam Bray alb64 1995
Vladimir The Bear vtb39 2015
Charlie The Horse cth44 2016
users
Tuesday, May 28, 13
SAMPLE MODEL
class User < ActiveRecord::Baseend
Tuesday, May 28, 13
views
Tuesday, May 28, 13
Tuesday, May 28, 13
VIEWS
Views are templates for how your web pages look.
Variables created in the respective controller are used to insert relevant information into the template.
Tuesday, May 28, 13
VIEWS
Views use Embedded RuBy (ERB) to substitute data into the template.
<% #ruby here is run, but not output %>
<%= #ruby here is run and output %>
Tuesday, May 28, 13
SAMPLE VIEW
<% @users.each do |user| %> <%= user.name %><% end %>
Tuesday, May 28, 13