Beruflich Dokumente
Kultur Dokumente
org
created by
Thiscontentisavailablefreeon h1p://RailsForZombies.org
created by
Requisitos:
TryRuby.org
Episodio #1
A fondo en el CRUD
Columnas
(tenemos 3)
CRUD
{
tweets
(tenemos 4)
Filas
CRUD
id status zombi
DESAFO ZOMBI #1
Obten un hash del tweet con id = 3
ResultADO
b = { :status => "I just ate some delicious brains", :zombie => "Jim" }
Hash
CRUD
b = { :status => "I just ate some delicious brains", :zombie => "Jim" } puts b[:status] "I just ate some delicious brains" puts b[:zombie] "Jim" puts b[:zombie] + " said " + b[:status] "Jim said I just ate some delicious brains"
tweets
id 1 2 3 4
status Where can I get a good bite to eat? My left arm is missing, but I don't care. I just ate some delicious brains. OMG, my ngers turned green. #FML
CRUD
"Jim"
CRUD
t = Tweet.find(3) puts t[:id]
puts t.id
a Igu la
RESPUESTA puts
t.id
3
"I just ate some delicious brains."
"Jim"
CRUD
t = Tweet.find(3)
Pluraliza
tweets
id 1 2 3 4 status Where can I get a good bite to eat? My left arm is missing, but I don't care. I just ate some delicious brains. OMG, my ngers turned green. #FML zombie Ash Bob Jim Ash
Create
Read
Tweet.find(3)
Update
Delete
t = Tweet.find(3) t.destroy
Create
t = Tweet.new t.status = "I <3 t.zombie = "Jim" t.save
Sintaxis
Sintaxis alternativa
s el amo sign o a n ente que brains." ticam om s en aut ijao F igna e as tros. S noso d. i por
Read
Tweet.find(2) Tweet.find(3, 4, 5) Tweet.first Tweet.last Tweet.all Tweet.count Tweet.order(:zombie) Tweet.limit(10) # Devuelve un objeto # Devuelve un array
Sintaxis
# Devuelve el primer tweet # Devuelve el ltimo tweet # Devuelve todos los tweets # Devuelve el num.de tweets # Todos ordenados por zombi # Solo 10 tweets # Solo tweets de Ash
encadenamiento de mtodos
Update
t = Tweet.find(3) t.zombie = "EyeballChomper" t.save
Sintaxis
t = Tweet.find(2) t.attributes = { :status => "Can I munch your eyeballs?", :zombie => "EyeballChomper" } t.save t = Tweet.find(2) t.update_attributes( :status => "Can I munch your eyeballs?", :zombie => "EyeballChomper" )
Delete
t = Tweet.find(2) t.destroy Tweet.find(2).destroy Tweet.destroy_all
Sintaxis
PRCTICA ZOMBI 1
http://railsforzombies.org Para cuando llegues al video del Lab 2 No te molestes en ver los videos Descarga las diapositivas para que puedas recordar la sintaxis
Thiscontentisavailablefreeon h1p://RailsForZombies.org
created by
t = Tweet.find(3) Tweet
Modelos
?
tweets
id 1 2 3 4
app/models/tweet.rb
class Tweet < ActiveRecord::Base end
status Where can I get a good bite to eat? My left arm is missing, but I don't care. I just ate some delicious brains. OMG, my ngers turned green. #FML
Tweet
app/models/tweet.rb
class Tweet < ActiveRecord::Base end
MODELOS
tweets
id 1 2 3 4
status Where can I get a good bite to eat? My left arm is missing, but I don't care. I just ate some delicious brains. OMG, my ngers turned green. #FML
app/models/tweet.rb
class Tweet < ActiveRecord::Base end
MODELOS
instancia de Tweet
Tweet #3
t = Tweet.find(3)
clase
tweets
id 1 2 3 4 status Where can I get a good bite to eat? My left arm is missing, but I don't care. I just ate some delicious brains. OMG, my ngers turned green. #FML zombie Ash Bob Jim Ash
Validaciones?
id 1 2 3 4 5 status Where can I get a good bite to eat? My left arm is missing, but I don't care. I just ate some delicious brains. OMG, my ngers turned green. #FML zombie Ash Bob Jim Ash
t = Tweet.new t.save
VALIDACIO NE
=> #<Tweet id: nil, status: nil, zombie: nil> > t.save => false > t.errors => {:status=>["can't be blank"]} > t.errors[:status] => "can't be blank"
validates_presence_of :status validates_numericality_of :fingers validates_uniqueness_of :toothmarks validates_confirmation_of :password validates_acceptance_of :zombification
VALIDACIO NE
validates_length_of :password, :minimum => 3 validates_format_of :email, :with => /regex/i validates_inclusion_of :age, :in => 21..99 validates_exclusion_of :age, :in => 0...21, :message => Sorry you must be over 21
tributo A
acin Valid
validates :status, :presence => true validates :status, :length => { :minimum => 3 }
VALIDACIO NE
:presence => true :uniqueness => true :numericality => true :length => { :minimum => 0, :maximum => 2000 } :format => { :with => /.*/ } :inclusion => { :in => [1,2,3] } :exclusion => { :in => [1,2,3] } :acceptance => true :confirmation => true
ONES ELACI R
tweets
id 1 2 3 4
RELACION
zombie Ash Bob Jim Ash
ES
status Where can I get a good bite to eat? My left arm is missing, but I don't care. I just ate some delicious brains. OMG, my ngers turned green. #FML
tweets
id 1 2 3 4
RELACION
ES
status Where can I get a good bite to eat? My left arm is missing, but I don't care. I just ate some delicious brains. OMG, my ngers turned green. #FML
zombies
id 1 2 3 Ash Bob Jim
name
graveyard Glen Haven Memorial Cemetery Chapel Hill Cemetery My Fathers Basement
tweets
id 1 2 3 4
RELACION
zombie_id 1 2 3 1
ES
status Where can I get a good bite to eat? My left arm is missing, but I don't care. I just ate some delicious brains. OMG, my ngers turned green. #FML
zombies
id 1 2 3 Ash Bob Jim
name
graveyard Glen Haven Memorial Cemetery Chapel Hill Cemetery My Fathers Basement
tweets
id 1 2 3 4
RELACION
zombie_id 1 2 3 1 2
ES
status Where can I get a good bite to eat? My left arm is missing, but I don't care. I just ate some delicious brains. OMG, my ngers turned green. #FML
zombies
id 1 2 3 Ash Bob Jim
name
graveyard Glen Haven Memorial Cemetery Chapel Hill Cemetery My Fathers Basement
ingular S
tweets
id
Plural
status zombie_id 1 2 3 1
1 Where can I get a good bite to eat? 2 My left arm is missing, but I don't care. 3 I just ate some delicious brains. 4 OMG, my ngers turned green. #FML
zombies
id 1 2 3 name Ash Bob Jim graveyard Glen Haven Memorial Cemetery Chapel Hill Cemetery My Fathers Basement
> z = Zombie.find(2) => #<Zombie id: 2, name: "Bob", graveyard: "Chapel Hill Cemetery">
RELACION
ES
> t = Tweet.create(:status => "Your eyelids taste like bacon.", :zombie => z) => #<Tweet id: 5, status: "Your eyelids taste like bacon.", zombie_id: 2> > t.zombie => #<Zombie id: 2, name: "Bob", graveyard: "Chapel Hill Cemetery"> > t.zombie.name => "Bob" > ash = Zombie.find(1) => #<Zombie id: 1, name: "Ash", graveyard: "Glen Haven Cemetery"> > ash.tweets.count => 4 > ash.tweets => [#<Tweet id: 1, status: "Where can I get a good bite to eat?", zombie_id: 1>, #<Tweet id: 4, status: "OMG, my fingers turned green. #FML", zombie_id: 1>]
PRCTICA ZOMBI 2
Thiscontentisavailablefreeon h1p://RailsForZombies.org
created by
VISTAS
Views
Models
4 Componentes
VISTAS
Embedded Ruby
Ruby empotrado en HTML
index.html.erb show.html.erb
Mostrar un tweet
<% ... %>
Evaluar Ruby
/app/views/tweets/show.html.erb
<!DOCTYPE html> <html> <head><title>Twitter for Zombies</title></head> <body> <img src="/images/twitter.png" /> <% tweet = Tweet.find(1) %> <h1><%= tweet.status %></h1> <p>Posted by <%= tweet.zombie.name %></p> </body></html>
Mostrar un tweet
/app/views/layouts/application.html.erb
<!DOCTYPE html> <html> <head><title>Twitter for Zombies</title></head> <body> <img src="/images/twitter.png" />
/app/views/tweets/show.html.erb
<% tweet = Tweet.find(1) %> <h1><%= tweet.status %></h1> <p>Posted by <%= tweet.zombie.name %></p>
VISTAS
La plantilla principal
application.html.erb
index.html.erb show.html.erb
Componentes adicionales
/app/views/layouts/application.html.erb
<!DOCTYPE html> <html> <head> <title>Twitter for Zombies</title> </head> <body> <img src="/images/twitter.png" />
Componentes adicionales
/app/views/layouts/application.html.erb
<!DOCTYPE html> <html> <head> <title>Twitter for Zombies</title> <%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> <%= csrf_meta_tag %> </head> <body> <img src="/images/twitter.png" />
Componentes adicionales
<%= stylesheet_link_tag :all %>
Incluye
Renderiza
<link href="/stylesheets/scaffold.css" media="screen" rel="stylesheet" type="text/css" />
Componentes adicionales
<%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %>
Renderiza
<script <script <script <script <script <script
src="/javascripts/prototype.js" type="text/javascript"></script> src="/javascripts/effects.js" type="text/javascript"></script> src="/javascripts/dragdrop.js" type="text/javascript"></script> src="/javascripts/controls.js" type="text/javascript"></script> src="/javascripts/rails.js" type="text/javascript"></script> src="/javascripts/application.js" type="text/javascript"></script>
Componentes adicionales
<%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> <%= csrf_meta_tag %>
m">
Renderiza
Tu web
Ejemplo
<img src="/images/twitter.png" />
Aadir un enlace
/app/views/tweets/show.html.erb
... <p>Posted by <%= tweet.zombie.name %></p>
al ar nlaz E
bi zom
%>
Renderiza
<a href="/zombies/1">Ash</a>
Texto enlace
Objeto a mostrar
Mtodo
link_to
Mtodo
link_to
2. Mirar en api.rubyonrails.org
(y buscar por link_to)
http://api.rubyonrails.org
Mtodo
link_to
3. API Dock
(documentacin online de Ruby y Rails)
http://apidock.com/rails
Mtodo
link_to
http://railsapi.com/
<%= link_to @tweet.zombie.name, @tweet.zombie, :confirm => "Are you sure?" %>
VISTAS
La plantilla principal
application.html.erb
index.html.erb show.html.erb
Listar tweets
/app/views/tweets/index.html.erb
<h1>Listing tweets</h1> <table> <tr> <th>Status</th> <th>Zombie</th> </tr>
Views
Lo que devuelven
Tweet
clase
<% Tweet.all.each do |tweet| %> <tr> <td><%= tweet.status %></td> <td><%= tweet.zombie.name %></td> </tr> <% end %>
</table>
un tweet
Crear enlaces
/app/views/tweets/index.html.erb
<% Tweet.all.each do |tweet| %> <tr> <td><%= tweet.status %></td> <td><%= tweet.zombie.name %></td> </tr> <% end %>
VISTAS
Crear enlaces
/app/views/tweets/index.html.erb
<% Tweet.all.each do |tweet| %> <tr> <td><%= link_to tweet.status, tweet %></td> <td><%= tweet.zombie.name %></td> </tr> <% end %>
VISTAS
Crear enlaces
/app/views/tweets/index.html.erb
<% Tweet.all.each do |tweet| %> <tr> <td><%= link_to tweet.status, tweet %></td> <td><%= link_to tweet.zombie.name, tweet.zombie %></td> </tr> <% end %>
VISTAS
<% Tweet.all.each do |tweet| %> <tr> <td><%= link_to tweet.status, tweet %></td> <td><%= link_to tweet.zombie.name, tweet.zombie %></td> </tr> <% end %>
<% tweets = Tweet.all %> <% ... <% end %> .each do |tweet| %>
<% tweets = Tweet.all %> <% tweets.each do |tweet| %> ... <% end %>
<% tweets = Tweet.all %> <% tweets.each do |tweet| %> ... <% end %>
Accin
Cdigo
URL generada
tweets_path new_tweet_path
/tweets /tweets/new
tweet = Tweet.find(1)
Accin Cdigo
tweet edit_tweet_path(tweet)
/tweets/1 /tweets/1/edit
PRCTICA ZOMBI 3
Thiscontentisavailablefreeon h1p://RailsForZombies.org
created by
ros reb
Mostrar un tweet
/app/views/tweets/show.html.erb
<!DOCTYPE html> <html> <head><title>Twitter for Zombies</title></head> <body> <img src="/images/twitter.png" /> <% tweet = Tweet.find(1) %> <h1><%= tweet.status %></h1> <p>Posted by <%= tweet.zombie.name %></p> </body></html>
Peticin
/tweets/1
Controller
/app/views/tweets/show.html.erb
<% tweet = Tweet.find(1) %> <h1><%= tweet.status %></h1> <p>Posted by <%= tweet.zombie.name %></p>
Peticin
tweets /tweets/1
Controller
/app/views/tweets/show.html.erb tweets
<% tweet = Tweet.find(1) %> <h1><%= tweet.status %></h1> <p>Posted by <%= tweet.zombie.name %></p>
Peticin
/tweets/1
/app/controllers/tweets_controller.rb
class TweetsController < ApplicationController end ...
/app/views/tweets/show.html.erb
<% tweet = Tweet.find(1) %> <h1><%= tweet.status %></h1> <p>Posted by <%= tweet.zombie.name %></p>
Peticin
/tweets/1
/app/controllers/tweets_controller.rb
class TweetsController < ApplicationController def show end end
/app/views/tweets/show.html.erb
<% tweet = Tweet.find(1) %> <h1><%= tweet.status %></h1> <p>Posted by <%= tweet.zombie.name %></p>
Peticin
/tweets/1
/app/controllers/tweets_controller.rb
class TweetsController < ApplicationController def show end end
/app/views/tweets/show.html.erb show
<% tweet = Tweet.find(1) %> <h1><%= tweet.status %></h1> <p>Posted by <%= tweet.zombie.name %></p>
Peticin
/tweets/1
/app/controllers/tweets_controller.rb
class TweetsController < ApplicationController def show end end
/app/views/tweets/show.html.erb
<% tweet = Tweet.find(1) %> <h1><%= tweet.status %></h1> <p>Posted by <%= tweet.zombie.name %></p>
Peticin
/tweets/1
/app/controllers/tweets_controller.rb
class TweetsController < ApplicationController def show tweet = Tweet.find(1) end end
/app/views/tweets/show.html.erb
<h1><%= tweet.status %></h1> <p>Posted by <%= tweet.zombie.name %></p>
Variable de instancia
@
/app/controllers/tweets_controller.rb
def show @ tweet = Tweet.find(1) end end
Peticin
/tweets/1
/app/views/tweets/show.html.erb
<h1><%= @ tweet.status %></h1> <p>Posted by <%= @ tweet.zombie.name %></p>
Render
/app/controllers/tweets_controller.rb
Peticin
/tweets/1
class TweetsController < ApplicationController def show @ tweet = Tweet.find(1) end end
/app/views/tweets/status.html.erb
<h1><%= @ tweet.status %></h1> <p>Posted by <%= @ tweet.zombie.name %></p>
Render
/app/controllers/tweets_controller.rb
def show @ tweet = Tweet.find(1) render :action => 'status' end end
Peticin
/tweets/1
/app/views/tweets/status.html.erb
<h1><%= @ tweet.status %></h1> <p>Posted by <%= @ tweet.zombie.name %></p>
Render
/app/controllers/tweets_controller.rb
def show @ tweet = Tweet.find(1) render :action => 'status' end end
Peticin
/tweets/1 /tweets/2 /tweets/3 /tweets/4 /tweets/5
/app/views/tweets/status.html.erb
<h1><%= @ tweet.status %></h1> <p>Posted by <%= @ tweet.zombie.name %></p>
Render
/app/controllers/tweets_controller.rb
def show @ tweet = Tweet.find(1) render :action => 'status' end end
Peticin
/tweets/1 /tweets/2 /tweets/3 /tweets/4 /tweets/5
params[:id]
/app/views/tweets/status.html.erb
<h1><%= @ tweet.status %></h1> <p>Posted by <%= @ tweet.zombie.name %></p>
Render
params = { :id => "1" }
Peticin
/tweets/1 /tweets/2 /tweets/3 /tweets/4 /tweets/5
params[:id]
/app/controllers/tweets_controller.rb
class TweetsController < ApplicationController def show @ tweet = Tweet.find(params[:id]) render :action => 'status' end end
/app/views/tweets/status.html.erb
<h1><%= @ tweet.status %></h1> <p>Posted by <%= @ tweet.zombie.name %></p>
Parmetros
params = { :status => "Im dead" }
Peticin
Peticin
xml /tweets/1 xml? json?
<?xml version="1.0" encoding="UTF-8"?> <tweet> <id type="integer">1</id> <status>Where can I get a good bite to eat?</status> <zombie-id type="integer">1</zombie-id> </tweet>
json
{"tweet":{"id":1,"status":"Where can I get a good bite to eat?","zombie_id":1}}
class TweetsController < ApplicationController def show @tweet = Tweet.find(params[:id]) respond_to do format.html format.xml format.json end end |format| # show.html.erb { render :xml => @tweet } { render :json => @tweet }
Request
/tweets/1 xml? json?
/tweets/1.xml
<?xml version="1.0" encoding="UTF-8"?> <tweet> <id type="integer">1</id> <status>Where can I get a good bite to eat?</status> <zombie-id type="integer">1</zombie-id> </tweet>
/tweets/1.json
{"tweet":{"id":1,"status":"Where can I get a good bite to eat?","zombie_id":1}}
Acciones Controller
/app/controllers/tweets_controller.rb
def index def show def new def edit def create def update def destroy end
Peticin
Listar todos los tweets Mostrar un tweet Formulario de nuevo tweet Fomulario para editar tweet Crear nuevo tweet Actualizar un tweet Borrar un tweet
Vista
Aadimos autorizacin
def edit
Aadimos autorizacin
/app/controllers/tweets_controller.rb
def edit @tweet = Tweet.find(params[:id]) end
Aadimos autorizacin
Aadimos autorizacin
Aadimos autorizacin
Redirect y Flash
/app/controllers/tweets_controller.rb
def edit @tweet = Tweet.find(params[:id])
Peticin
if session[:zombie_id] != @tweet.zombie_id flash[:notice] = "Sorry, you cant edit this tweet" redirect_to(tweets_path) end end end
Funciona como un hash por usuario Para enviar mensajes al usuario Redirigir la peticin
Redirect y Flash
/app/controllers/tweets_controller.rb
def edit @tweet = Tweet.find(params[:id])
Peticin
if session[:zombie_id] != @tweet.zombie_id redirect_to(tweets_path , :notice => "Sorry, you cant edit this tweet") end end end
Avisos en Layouts
/app/views/layouts/application.html.erb
<!DOCTYPE html> <html> <head> <title>Twitter for Zombies</title> <%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> <%= csrf_meta_tag %> </head> <body> <img src="/images/twitter.png" />
Avisos en Layouts
/app/views/layouts/application.html.erb
<!DOCTYPE html> <html> <head> <title>Twitter for Zombies</title> <%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> <%= csrf_meta_tag %> </head> <body> <img src="/images/twitter.png" /> <% if flash[:notice] %> <div id="notice"><%= flash[:notice] %></div> <% end %>
Aadimos autorizacin
Aadimos autorizacin
Acciones Controller
/app/controllers/tweets_controller.rb
def index def show def new def edit def create def update def destroy end
Peticin
Listar todos los tweets Mostrar un tweet Formulario de nuevo tweet Formulario para editar tweet Crear nuevo tweet Actualizar tweet Borrar tweet
Vista
Before Filters
/app/controllers/tweets_controller.rb
Peticin
def edit
Vista
Necesitan
autorizacin
Before Filters
/app/controllers/tweets_controller.rb
Peticin
class TweetsController < ApplicationController def edit @tweet = Tweet.find(params[:id]) ... end def update @tweet = Tweet.find(params[:id]) ... end def destroy @tweet = Tweet.find(params[:id]) ... end end
Before Filters
/app/controllers/tweets_controller.rb
Peticin
class TweetsController < ApplicationController before_filter :get_tweet, :only => [:edit, :update, :destroy] def get_tweet @tweet = Tweet.find(params[:id]) end def edit ... end def update ... end def destroy ... end end
Before Filters
/app/controllers/tweets_controller.rb
Peticin
class TweetsController < ApplicationController before_filter :get_tweet, :only => [:edit, :update, :destroy] before_filter :check_auth, :only => [:edit, :update, :destroy] def get_tweet @tweet = Tweet.find(params[:id]) end def check_auth if session[:zombie_id] != @tweet.zombie_id flash[:notice] = "Sorry, you cant edit this tweet" redirect_to tweets_path end end def edit def update def destroy end
Aadimos autorizacin
Thiscontentisavailablefreeon h1p://RailsForZombies.org
created by
Episodio #5
Enrutando en la oscuridad
Action
Code
tweets_path new_tweet_path
/tweets /tweets/new
tweet = Tweet.find(1)
Action Code
tweet edit_tweet_path(tweet)
/tweets/1 /tweets/1/edit
y estas acciones
/app/controllers/tweets_controller.rb
def index def show def new def edit def create def update def destroy end
Peticin
Listar todos los tweets Mostrar un tweet Formulario de nuevo tweet Formulario para editar tweet Crear tweet Actualizar un tweet Borrar un teet
Vista
zombie_twitter cong
routes.rb
Rutas custom
http://localhost:3000/new_tweet
renderiza http://localhost:3000/tweets/new
class TweetsController def new ... end end
/cong/routes.rb
ZombieTwitter::Application.routes.draw do |map| resources :tweets match 'new_tweet' => "Tweets#new" end
Ruta
Controller
Accin
Named Routes
http://localhost:3000/all
renderiza
http://localhost:3000/tweets
tweets_path no funcionara
%>
Named Routes
http://localhost:3000/all
renderiza
http://localhost:3000/tweets
redirige a
Redirect
http://localhost:3000/all
redirige a
http://localhost:3000/tweets
Ruta raz
http://localhost:3000/
renderiza
http://localhost:3000/tweets
Controller
Accin
Parmetros en rutas
/local_tweets/32828 /local_tweets/32801
/app/controllers/tweets_controller.rb
def index if params[:zipcode] @tweets = Tweet.where(:zipcode => params[:zipcode]) else @tweets = Tweet.all end respond_to do |format| format.html # index.html.erb format.xml { render :xml => @tweets } end end
Parmetros en rutas
/local_tweets/32828 /local_tweets/32801
Parmetros en rutas
/github /greggpollack /eallam /envylabs
/app/controllers/tweets_controller.rb
def index if params[:name] @zombie = Zombie.where(:name => params[:name]).first @tweets = @zombie.tweets else @tweets = Tweet.all end end
PRCTICA ZOMBI 5
Thiscontentisavailablefreeon h1p://RailsForZombies.org
created by
Creative Commons
name Toothless Zombie Still Eating Brains? brains! Blue Eyed Zombie zombie puberty Zombie March Chicago construction sign author Ateo Fiel SanFranAnnie ginnerobot Josh Jensen zenobia_joy Eric Ingrum underbiteman URL
http://www.ickr.com/photos/ateoel/292853829/ http://www.ickr.com/photos/sanfranannie/4557247098/ http://www.ickr.com/photos/ginnerobot/2978178952/ http://www.ickr.com/photos/jwjensen/3919674567/ http://www.ickr.com/photos/zenobia_joy/4006626151/ http://www.ickr.com/photos/ericingrum/2600434956/ http://www.ickr.com/photos/underbiteman/2638246638/ http://www.ickr.com/photos/bobjagendorf/3978792454/ http://www.ickr.com/photos/doviende/38013223