135
This content is available free on h1p://RailsForZombies.org created by

Rails for Zombies Slides Spanish

Embed Size (px)

Citation preview

Page 1: Rails for Zombies Slides Spanish

Thiscontentisavailablefreeonh1p://RailsForZombies.org

created by

Page 2: Rails for Zombies Slides Spanish

Una introduccion a RailsEpisodio #1

Thiscontentisavailablefreeonh1p://RailsForZombies.org

created by

Page 3: Rails for Zombies Slides Spanish

Requisitos:

TryRuby.org

Page 4: Rails for Zombies Slides Spanish

Episodio #1A fondo en el CRUD

Page 5: Rails for Zombies Slides Spanish

PARA ZOMBIS!!PARA ZOMBIS!!

Page 6: Rails for Zombies Slides Spanish

{ CRUD

tweets

Filas {(tenemos 4)

Columnas(tenemos 3)

Page 7: Rails for Zombies Slides Spanish

id status zombi

Obten un hash del tweet con id = 3DESAFÍO ZOMBI #1

CRUD

b = { :status => "I just ate some delicious brains", :zombie => "Jim" }

ResultADO

Page 8: Rails for Zombies Slides Spanish

HashSerie de pares clave valor

puts b[:status]

puts b[:zombie]

puts b[:zombie] + " said " + b[:status]

CRUD

b = { :status => "I just ate some delicious brains", :zombie => "Jim" }

"Jim said I just ate some delicious brains"

"Jim"

"I just ate some delicious brains"

Page 9: Rails for Zombies Slides Spanish

tweets

Obten un hash del tweet con id = 3DESAFÍO ZOMBI #1

id status zombie

1 Where can I get a good bite to eat? Ash

2 My left arm is missing, but I don't care. Bob

3 I just ate some delicious brains. Jim

4 OMG, my fingers turned green. #FML Ash

RESPUESTA3puts t[:id]

t = Tweet.find(3)

puts t[:status] "I just ate some delicious brains."

puts t[:zombie] "Jim"

CRUD

Page 10: Rails for Zombies Slides Spanish

puts t.id

puts t.status

puts t.zombie

Igual a

CRUD

puts t[:id]

t = Tweet.find(3)

puts t[:status]

puts t[:zombie]

RESPUESTA 3puts t.id

puts t.status "I just ate some delicious brains."

puts t.zombie "Jim"

Page 11: Rails for Zombies Slides Spanish

CRUDt = Tweet.find(3)

tweetsid status zombie

1 Where can I get a good bite to eat? Ash

2 My left arm is missing, but I don't care. Bob

3 I just ate some delicious brains. Jim

4 OMG, my fingers turned green. #FML Ash

Pluraliza

Page 12: Rails for Zombies Slides Spanish

C

R

U

D

Page 13: Rails for Zombies Slides Spanish

Create Crear

ReadLeer

UpdateActualizar

DeleteBorrar

Page 14: Rails for Zombies Slides Spanish

Create

Read

Update

Delete

Tweet.find(3)

t = Tweet.find(3)t.zombie = "EyeballChomper"t.save

t = Tweet.find(3)t.destroy

t = Tweet.newt.status = "I <3 brains."t.save

Page 15: Rails for Zombies Slides Spanish

Create Sintaxis

t = Tweet.newt.status = "I <3 brains."t.zombie = "Jim"t.save

Sintaxis alternativat = Tweet.new(:status => "I <3 brains", :zombie => "Jim")t.save

Tweet.create(:status => "I <3 brains", :zombie => "Jim")

Fijaos en que

no asignamos

el

id. Se asigna

automáticame

nte

por nosotros.

Page 16: Rails for Zombies Slides Spanish

Read Sintaxis

encadenamiento de métodos

Tweet.find(2) # Devuelve un objeto

Tweet.find(3, 4, 5) # Devuelve un array

Tweet.first # Devuelve el primer tweet

Tweet.last # Devuelve el último tweet

Tweet.all # Devuelve todos los tweets

Tweet.order(:zombie) # Todos ordenados por zombi

Tweet.limit(10) # Solo 10 tweets

Tweet.where(:zombie => "ash") # Solo tweets de Ash

Tweet.where(:zombie => "ash").order(:zombie).limit(10)

Tweet.count # Devuelve el num.de tweets

Page 17: Rails for Zombies Slides Spanish

Update Sintaxis

t = Tweet.find(3)t.zombie = "EyeballChomper"t.save

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" )

Page 18: Rails for Zombies Slides Spanish

t = Tweet.find(2)t.destroy

Tweet.find(2).destroy

Delete Sintaxis

Tweet.destroy_all

Page 19: Rails for Zombies Slides Spanish

PRÁCTICA ZOMBI 1PRÁCTICA ZOMBI 1http://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

Page 20: Rails for Zombies Slides Spanish

Una introduccion a RailsEpisodio #2

Thiscontentisavailablefreeonh1p://RailsForZombies.org

created by

Page 21: Rails for Zombies Slides Spanish

Episodio #2Los Modelos saben a pollo

Page 22: Rails for Zombies Slides Spanish

t = Tweet.find(3)

tweetsid status zombie

1 Where can I get a good bite to eat? Ash

2 My left arm is missing, but I don't care. Bob

3 I just ate some delicious brains. Jim

4 OMG, my fingers turned green. #FML Ash

Tweet

? class Tweet < ActiveRecord::Base end

app/models/tweet.rb

Modelos

Page 23: Rails for Zombies Slides Spanish

MODELOS

tweetsid status zombie

1 Where can I get a good bite to eat? Ash

2 My left arm is missing, but I don't care. Bob

3 I just ate some delicious brains. Jim

4 OMG, my fingers turned green. #FML Ash

Tweet

class Tweet < ActiveRecord::Base end

app/models/tweet.rb< ActiveRecord::Base

Asocia la clase a la tabla

Page 24: Rails for Zombies Slides Spanish

tweets

class Tweet < ActiveRecord::Base end

Tweet.find(3)

clase

Tweet #3t =instancia de Tweet

MODELOSapp/models/tweet.rb

id status zombie

1 Where can I get a good bite to eat? Ash

2 My left arm is missing, but I don't care. Bob

3 I just ate some delicious brains. Jim

4 OMG, my fingers turned green. #FML Ash

Page 25: Rails for Zombies Slides Spanish

¿Validaciones?id status zombie

1 Where can I get a good bite to eat? Ash

2 My left arm is missing, but I don't care. Bob

3 I just ate some delicious brains. Jim

4 OMG, my fingers turned green. #FML Ash

t = Tweet.newt.save

5

Page 26: Rails for Zombies Slides Spanish

VALIDACIONESclass Tweet < ActiveRecord::Base

end

validates_presence_of :status

app/models/tweet.rb

> t = Tweet.new => #<Tweet id: nil, status: nil, zombie: nil> > t.save => false > t.errors => {:status=>["can't be blank"]}> t.errors[:status] => "can't be blank"

Page 27: Rails for Zombies Slides Spanish

VALIDACIONESvalidates_presence_of :status

validates_numericality_of :fingers

validates_uniqueness_of :toothmarks

validates_confirmation_of :password

validates_acceptance_of :zombification

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”

Page 28: Rails for Zombies Slides Spanish

VALIDACIONESvalidates :status, :presence => truevalidates :status, :length => { :minimum => 3 }

validates :status, :presence => true, :length => { :minimum => 3 }

: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

Atributo Validación

Page 29: Rails for Zombies Slides Spanish

RELACIONES

Porque siempre viajan en manadas

RELACIONES

Page 30: Rails for Zombies Slides Spanish

RELACIONEStweets

id status zombie

1 Where can I get a good bite to eat? Ash

2 My left arm is missing, but I don't care. Bob

3 I just ate some delicious brains. Jim

4 OMG, my fingers turned green. #FML Ash

Page 31: Rails for Zombies Slides Spanish

RELACIONEStweets

id status

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 fingers turned green. #FML

zombiesid name graveyard

1 Ash Glen Haven Memorial Cemetery

2 Bob Chapel Hill Cemetery

3 Jim My Father’s Basement

Page 32: Rails for Zombies Slides Spanish

RELACIONEStweetsid status zombie_id1 Where can I get a good bite to eat? 12 My left arm is missing, but I don't care. 23 I just ate some delicious brains. 34 OMG, my fingers turned green. #FML 1

zombiesid name graveyard

1 Ash Glen Haven Memorial Cemetery

2 Bob Chapel Hill Cemetery

3 Jim My Father’s Basement

Page 33: Rails for Zombies Slides Spanish

RELACIONES

5 Your eyelids taste like bacon. 2

tweetsid status zombie_id1 Where can I get a good bite to eat? 12 My left arm is missing, but I don't care. 23 I just ate some delicious brains. 34 OMG, my fingers turned green. #FML 1

zombiesid name graveyard

1 Ash Glen Haven Memorial Cemetery

2 Bob Chapel Hill Cemetery

3 Jim My Father’s Basement

Page 34: Rails for Zombies Slides Spanish

A Tweet a Zombiebelongs to

tweetsid status zombie_id

1 Where can I get a good bite to eat? 1

2 My left arm is missing, but I don't care. 2

3 I just ate some delicious brains. 3

4 OMG, my fingers turned green. #FML 1

zombiesid name graveyard

1 Ash Glen Haven Memorial Cemetery

2 Bob Chapel Hill Cemetery

3 Jim My Father’s Basement

class Tweet < ActiveRecord::Base

end

app/models/tweet.rb

belongs_to :zombie

class Zombie < ActiveRecord::Base

end

app/models/zombie.rb

has_many :tweets

A Zombie Tweetshas many

SingularPlural

Page 35: Rails for Zombies Slides Spanish

RELACIONES> z = Zombie.find(2) => #<Zombie id: 2, name: "Bob", graveyard: "Chapel Hill Cemetery">

> 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 => [#<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>]

> ash.tweets.count => 4

A Tweet a Zombiebelongs to

Page 36: Rails for Zombies Slides Spanish

PRÁCTICA ZOMBI 2PRÁCTICA ZOMBI 2

Page 37: Rails for Zombies Slides Spanish

Una introduccion a RailsEpisodio #3

Thiscontentisavailablefreeonh1p://RailsForZombies.org

created by

Page 38: Rails for Zombies Slides Spanish

Episodio #3La vista no siempre es bonita

Me voy a comersu cerebrito

Page 39: Rails for Zombies Slides Spanish

VISTASNuestro Application Stack

4 Componentes

Views

Models

Page 40: Rails for Zombies Slides Spanish

app

views

zombie_twitter

VISTAS

zombies

tweets

index.html.erb

Edible Rotting Bodies

show.html.erb

Embedded Ruby

Listar todos los tweets

Ver un tweet

Ruby empotrado en HTML

Page 41: Rails for Zombies Slides Spanish

<!DOCTYPE html><html> <head><title>Twitter for Zombies</title></head><body> <img src="/images/twitter.png" />

</body></html>

<% tweet = Tweet.find(1) %>

<h1><%= tweet.status %></h1>

<p>Posted by <%= tweet.zombie.name %></p>

/app/views/tweets/show.html.erb

Mostrar un tweet

TÍO, ESTE CÓDIGOHUELE MAL...(por 2 razones)

<% ... %>

<%= ... %>Evaluar Ruby

Eval. e imprimir resultado

Page 42: Rails for Zombies Slides Spanish

/app/views/layouts/application.html.erb<!DOCTYPE html><html> <head><title>Twitter for Zombies</title></head><body> <img src="/images/twitter.png" />

</body></html>

<% tweet = Tweet.find(1) %>

<h1><%= tweet.status %></h1>

<p>Posted by <%= tweet.zombie.name %></p>

/app/views/tweets/show.html.erb

<%= yield %>

Mostrar un tweet

Page 43: Rails for Zombies Slides Spanish

application.html.erb

app

views

zombie_twitterVISTAS

zombies

tweets

index.html.erb

show.html.erb

Listar todos los tweets

Ver un tweet

layoutsLa plantilla principal

Page 44: Rails for Zombies Slides Spanish

/app/views/layouts/application.html.erb

Componentes adicionales

</head><body> <img src="/images/twitter.png" />

<%= yield %>

</body></html>

<!DOCTYPE html><html><head> <title>Twitter for Zombies</title>

Page 45: Rails for Zombies Slides Spanish

</head><body> <img src="/images/twitter.png" />

<%= yield %>

</body></html>

<!DOCTYPE html><html><head> <title>Twitter for Zombies</title> <%= stylesheet_link_tag :all %><%= javascript_include_tag :defaults %><%= csrf_meta_tag %>

/app/views/layouts/application.html.erb

Componentes adicionales

Page 46: Rails for Zombies Slides Spanish

<%= stylesheet_link_tag :all %>

<%= javascript_include_tag :defaults %>

<%= csrf_meta_tag %>

public

stylesheets

zombie_twitter

Incluye todas las hojasde estilo

<link href="/stylesheets/scaffold.css" media="screen" rel="stylesheet" type="text/css" />

Renderiza

Componentes adicionales

Page 47: Rails for Zombies Slides Spanish

<%= stylesheet_link_tag :all %>

<%= javascript_include_tag :defaults %>

<%= csrf_meta_tag %>

Incluye los JSpor defecto

<script src="/javascripts/prototype.js" type="text/javascript"></script><script src="/javascripts/effects.js" type="text/javascript"></script><script src="/javascripts/dragdrop.js" type="text/javascript"></script><script src="/javascripts/controls.js" type="text/javascript"></script><script src="/javascripts/rails.js" type="text/javascript"></script><script src="/javascripts/application.js" type="text/javascript"></script>

Framework de Javascript Prototype

public

javascripts

zombie_twitter

Renderiza

Componentes adicionales

Page 48: Rails for Zombies Slides Spanish

<%= stylesheet_link_tag :all %>

<%= javascript_include_tag :defaults %>

<%= csrf_meta_tag %>

<form target="http://yoursite.com">SITIO Hacker Zombi

Tu web

<meta name="csrf-param" content="authenticity_token"/><meta name="csrf-token" content="I+d..jI="/>

Esto es añadido automáticamente a los formularios

P. ej. spam de comentariosRenderiza

Componentes adicionales

Page 49: Rails for Zombies Slides Spanish

Ruta raíz e imágenes

http://ZombieTwitter.com/[algo]

Si existe e

n /public

se usa, si n

o va a Ra

ils

<img src="/images/twitter.png" />

public

stylesheets

zombie_twitter

javascripts

images

Ejemplo

Page 50: Rails for Zombies Slides Spanish

, zombie_path(tweet.zombie)

... <p>Posted by <%= tweet.zombie.name %></p>

/app/views/tweets/show.html.erb

Añadir un enlace

Enlazar al z

ombi

<%= link_to tweet.zombie.name %>

Texto enlace Ruta enlace (URL)

<a href="/zombies/1">Ash</a>Renderiza

<%= link_to tweet.zombie.name, tweet.zombie %>También se puede escribir así

Texto enlace Objeto a mostrar

Page 51: Rails for Zombies Slides Spanish

link_toMétodo

¿Qué opciones puedo

usar?

1. Mira el código fuente

git clone http://github.com/rails/rails.git

cd rails

Línea de comando

Abre tu editor y busca por “def link_to”

Page 52: Rails for Zombies Slides Spanish

link_toMétodo

¿Qué opciones puedo

usar?

2. Mirar en api.rubyonrails.org(y buscar por link_to)

Page 53: Rails for Zombies Slides Spanish

http://api.rubyonrails.org

Page 54: Rails for Zombies Slides Spanish

link_toMétodo

¿Qué opciones puedo

usar?

3. API Dock(documentación online de Ruby y Rails)

http://apidock.com/rails

Page 55: Rails for Zombies Slides Spanish
Page 56: Rails for Zombies Slides Spanish

link_toMétodo

¿Qué opciones puedo

usar?

4. Rails Searchable API Doc(local y online)

http://railsapi.com/

Page 58: Rails for Zombies Slides Spanish
Page 59: Rails for Zombies Slides Spanish

<%= link_to @tweet.zombie.name, @tweet.zombie, :confirm => "Are you sure?" %>

Page 60: Rails for Zombies Slides Spanish

application.html.erb

app

views

zombie_twitterVISTAS

zombies

tweets

index.html.erb

show.html.erb

Listar todos los tweets

Ver un tweet

layoutsLa plantilla principal

Page 61: Rails for Zombies Slides Spanish

ViewsListar tweets

/app/views/tweets/index.html.erb

Tweet

tweet

clase

un tweet

Tweet.all array de tweets

Lo que devuelven

tweet.statustweet.zombie.name

%></td>%></td>

</table>

<h1>Listing tweets</h1>

<table> <tr> <th>Status</th> <th>Zombie</th> </tr>

<% Tweet.all.each do |tweet| %> <tr> <td><%= <td><%= </tr><% end %>

Page 62: Rails for Zombies Slides Spanish

VISTASCrear enlaces/app/views/tweets/index.html.erb

tweet.statustweet.zombie.name

%></td>%></td>

<% Tweet.all.each do |tweet| %> <tr> <td><%= <td><%= </tr><% end %>

Page 63: Rails for Zombies Slides Spanish

VISTAS/app/views/tweets/index.html.erb

link_to tweet.statustweet.zombie.name

%></td>%></td>

<% Tweet.all.each do |tweet| %> <tr> <td><%= <td><%= </tr><% end %>

, tweet

Crear enlaces

Page 64: Rails for Zombies Slides Spanish

VISTAS/app/views/tweets/index.html.erb

link_to , tweet.zombie

Crear enlaces

link_to tweet.statustweet.zombie.name

%></td>%></td>

<% Tweet.all.each do |tweet| %> <tr> <td><%= <td><%= </tr><% end %>

, tweet

Page 65: Rails for Zombies Slides Spanish

¿Tabla vacía? VISTAS

Tweet.all<% .each do |tweet| %>

<% end %>

<tr> <td><%= link_to tweet.status, tweet %></td> <td><%= link_to tweet.zombie.name, tweet.zombie %></td> </tr>

Page 66: Rails for Zombies Slides Spanish

¿Tabla vacía? VISTAS

Tweet.all<% .each do |tweet| %>...

<% end %>

Page 67: Rails for Zombies Slides Spanish

¿Tabla vacía? VISTAS

Tweet.all

<% .each do |tweet| %>

<% tweets = %>tweets

...<% end %>

Page 68: Rails for Zombies Slides Spanish

¿Tabla vacía? VISTAS

Tweet.all

<% .each do |tweet| %>

<% tweets = %>

tweets...

<% end %>

<em>No tweets found</em><% end %>

<% if tweets.size == 0 %>

Page 69: Rails for Zombies Slides Spanish

¿Tabla vacia? VISTAS

Tweet.all

<% .each do |tweet| %>

<% tweets = %>

tweets...

<% end %>

<em>No tweets found</em><% end %>

<% if tweets.empty? %>

Page 70: Rails for Zombies Slides Spanish

¿Enlaces para editar y borrar?<% tweets.each do |tweet| %> <tr> <td><%= link_to tweet.status, tweet %></td> <td><%= link_to tweet.zombie.name, tweet.zombie %></td>

</tr><% end %>

<td><%= link_to "Edit", edit_tweet_path(tweet) %></td><td><%= link_to "Delete", tweet, :method => :delete %></td>

Page 71: Rails for Zombies Slides Spanish

Todos los enlaces para tweets

Acción Código URL generada

List all tweets tweets_path /tweetsNew tweet form new_tweet_path /tweets/new

Acción Código URL generada

Show a tweet tweet /tweets/1

Edit a tweet edit_tweet_path(tweet) /tweets/1/edit

Delete a tweet tweet, :method => :delete /tweets/1

tweet = Tweet.find(1) Estas rutas necesitan un tweet

<%= link_to "<link text>", <code> %>

Page 72: Rails for Zombies Slides Spanish

PRÁCTICA ZOMBI 3PRÁCTICA ZOMBI 3

Page 73: Rails for Zombies Slides Spanish

Una introduccion a RailsEpisodio #4

Thiscontentisavailablefreeonh1p://RailsForZombies.org

created by

Page 74: Rails for Zombies Slides Spanish

Episodio #4Los controllers se comen

cerebros

v

Page 75: Rails for Zombies Slides Spanish

Nuestro Application Stack

4 Componentes

Views

Models

Controllers

Page 76: Rails for Zombies Slides Spanish

<!DOCTYPE html><html> <head><title>Twitter for Zombies</title></head><body> <img src="/images/twitter.png" />

</body></html>

/app/views/tweets/show.html.erb

Mostrar untweet

TÍO, ESTE CÓDIGOHUELE MAL...

(lo arreglamos luego)

<% tweet = Tweet.find(1) %>

<h1><%= tweet.status %></h1>

<p>Posted by <%= tweet.zombie.name %></p>

Page 77: Rails for Zombies Slides Spanish

/app/views/tweets/show.html.erb<% tweet = Tweet.find(1) %>

<h1><%= tweet.status %></h1>

<p>Posted by <%= tweet.zombie.name %></p>

Petición/tweets/1

Controller

/app/controllers/tweets_controller.rb

tweets_controller.rb

app

controllers

zombie_twitter

Page 78: Rails for Zombies Slides Spanish

/app/views/tweets/show.html.erb<% tweet = Tweet.find(1) %>

<h1><%= tweet.status %></h1>

<p>Posted by <%= tweet.zombie.name %></p>

Petición/tweets/1

Controller

/app/controllers/tweets_controller.rb

app

controllers

zombie_twitter

tweets_controller.rb

tweets

tweets

tweets

Page 79: Rails for Zombies Slides Spanish

/app/views/tweets/show.html.erb<% tweet = Tweet.find(1) %>

<h1><%= tweet.status %></h1>

<p>Posted by <%= tweet.zombie.name %></p>

Petición/tweets/1

/app/controllers/tweets_controller.rb

class TweetsController < ApplicationController

end...

Page 80: Rails for Zombies Slides Spanish

/app/views/tweets/show.html.erb<% tweet = Tweet.find(1) %>

<h1><%= tweet.status %></h1>

<p>Posted by <%= tweet.zombie.name %></p>

Petición/tweets/1

/app/controllers/tweets_controller.rbclass TweetsController < ApplicationController

end

def show

end

Page 81: Rails for Zombies Slides Spanish

/app/views/tweets/show.html.erb<% tweet = Tweet.find(1) %>

<h1><%= tweet.status %></h1>

<p>Posted by <%= tweet.zombie.name %></p>

Petición/tweets/1

/app/controllers/tweets_controller.rbclass TweetsController < ApplicationController

end

def show

end

show

show

Page 82: Rails for Zombies Slides Spanish

/app/views/tweets/show.html.erb

<h1><%=

<p>Posted by <%=

Petición/tweets/1

/app/controllers/tweets_controller.rbclass TweetsController < ApplicationController

end

def show

end

<% %>

tweet.status %></h1>

tweet.zombie.name %></p>

)tweet = Tweet.find(1

Page 83: Rails for Zombies Slides Spanish

/app/views/tweets/show.html.erb <h1><%=

<p>Posted by <%=

Petición/tweets/1

/app/controllers/tweets_controller.rbclass TweetsController < ApplicationController

end

def show

end

tweet.status %></h1>

tweet.zombie.name %></p>

¿QUÉ PASA CONLAS VARIABLES?

)tweet = Tweet.find(1

Page 84: Rails for Zombies Slides Spanish

/app/views/tweets/show.html.erb <h1><%=

<p>Posted by <%=

Petición/tweets/1

/app/controllers/tweets_controller.rbclass TweetsController < ApplicationController

end

def show

end

tweet.status %></h1>

tweet.zombie.name %></p>

@

@

@Variable de instancia

@ )tweet = Tweet.find(1

Page 85: Rails for Zombies Slides Spanish

/app/views/tweets/status.html.erb <h1><%=

<p>Posted by <%=

Petición/tweets/1

/app/controllers/tweets_controller.rbclass TweetsController < ApplicationController

end

tweet.status %></h1>

tweet.zombie.name %></p>

@

@

end

def show

Render

@ )tweet = Tweet.find(1

Page 86: Rails for Zombies Slides Spanish

/app/views/tweets/status.html.erb <h1><%=

<p>Posted by <%=

Petición/tweets/1

/app/controllers/tweets_controller.rbclass TweetsController < ApplicationController

end

tweet.status %></h1>

tweet.zombie.name %></p>

@

@

Render

end

def show

render :action => 'status'@ )tweet = Tweet.find(1

Page 87: Rails for Zombies Slides Spanish

/app/views/tweets/status.html.erb <h1><%=

<p>Posted by <%=

Petición/tweets/1

/app/controllers/tweets_controller.rbclass TweetsController < ApplicationController

end

tweet.status %></h1>

tweet.zombie.name %></p>

@

@

Render

end

def show

render :action => 'status'

/tweets/2/tweets/3/tweets/4/tweets/5

@ )tweet = Tweet.find(1

Page 88: Rails for Zombies Slides Spanish

/app/views/tweets/status.html.erb <h1><%=

<p>Posted by <%=

Petición/tweets/1

/app/controllers/tweets_controller.rbclass TweetsController < ApplicationController

end

tweet.status %></h1>

tweet.zombie.name %></p>

@

@

@

Render

end

def show

render :action => 'status'

params[:id]

/tweets/2/tweets/3/tweets/4/tweets/5

)tweet = Tweet.find(1

Page 89: Rails for Zombies Slides Spanish

/app/views/tweets/status.html.erb <h1><%=

<p>Posted by <%=

Petición/tweets/1

/app/controllers/tweets_controller.rbclass TweetsController < ApplicationController

end

tweet.status %></h1>

tweet.zombie.name %></p>

@

@

@

Render

end

def show

render :action => 'status'

params[:id]

/tweets/2/tweets/3/tweets/4/tweets/5

)tweet = Tweet.find(params[:id]

params = { :id => "1" }

Page 90: Rails for Zombies Slides Spanish

PeticiónParámetros

@tweet = Tweet.create(:status => )params[:status]

params = { :status => "I’m dead" }

@tweet = Tweet.create(:status => params[:tweet][:status])

params = {:tweet => { :status => "I’m dead" }}

También lo podemos escribir así

@tweet = Tweet.create(params[:tweet])

Page 91: Rails for Zombies Slides Spanish

Petición/tweets/1

<?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>

{"tweet":{"id":1,"status":"Where can I get a good bite to eat?","zombie_id":1}}

xml? json?xml

json

Page 92: Rails for Zombies Slides Spanish

<?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>

{"tweet":{"id":1,"status":"Where can I get a good bite to eat?","zombie_id":1}}

xml

json/tweets/1.

/tweets/1.

class TweetsController < ApplicationController

def show @tweet = Tweet.find(params[:id])

end

end

Request/tweets/1xml? json?

respond_to do |format|format.html # show.html.erbformat.xml { render :xml => @tweet }format.json { render :json => @tweet }

Page 93: Rails for Zombies Slides Spanish

Petición

/app/controllers/tweets_controller.rb

class TweetsController < ApplicationController

end

Acciones Controller

def show

def index

Vistadef edit

def create

def update

def destroy

def new

Listar todos los tweetsMostrar un tweetFormulario de nuevo tweetFomulario para editar tweetCrear nuevo tweetActualizar un tweetBorrar un tweet

Page 94: Rails for Zombies Slides Spanish

Añadimos autorización

def edit

Page 95: Rails for Zombies Slides Spanish

Añadimos autorización

def edit

/app/controllers/tweets_controller.rb

end@tweet = Tweet.find(params[:id])

app

views

zombie_twitter

tweets

edit.html.erb

Page 96: Rails for Zombies Slides Spanish

Añadimos autorización

Page 97: Rails for Zombies Slides Spanish

Añadimos autorización

Page 98: Rails for Zombies Slides Spanish

Añadimos autorización

Page 99: Rails for Zombies Slides Spanish

Petición

/app/controllers/tweets_controller.rb

class TweetsController < ApplicationController

end

Redirect y Flash

def edit

end

if session[:zombie_id] != @tweet.zombie_id

redirect_to(tweets_pathend

@tweet = Tweet.find(params[:id])

session Funciona como un hash por usuarioflash[:notice] Para enviar mensajes al usuarioredirect_to <ruta> Redirigir la petición

flash[:notice] = "Sorry, you can’t edit this tweet")

Page 100: Rails for Zombies Slides Spanish

Petición

/app/controllers/tweets_controller.rb

class TweetsController < ApplicationController

end

Redirect y Flash

def edit

end

if session[:zombie_id] != @tweet.zombie_id

end

@tweet = Tweet.find(params[:id])

redirect_to(tweets_path"Sorry, you can’t edit this tweet")

,:notice =>

Sintaxis alternativa combinandoredirect & flash

Page 101: Rails for Zombies Slides Spanish

Avisos en Layouts

<!DOCTYPE html><html><head> <title>Twitter for Zombies</title> <%= stylesheet_link_tag :all %><%= javascript_include_tag :defaults %><%= csrf_meta_tag %>

/app/views/layouts/application.html.erb

</head><body> <img src="/images/twitter.png" />

<%= yield %>

</body></html>

Page 102: Rails for Zombies Slides Spanish

<!DOCTYPE html><html><head> <title>Twitter for Zombies</title> <%= stylesheet_link_tag :all %><%= javascript_include_tag :defaults %><%= csrf_meta_tag %>

/app/views/layouts/application.html.erb

</head><body> <img src="/images/twitter.png" />

<%= yield %>

</body></html>

<% if flash[:notice] %>

<% end %><div id="notice"><%= flash[:notice] %></div>

Avisos en Layouts

Page 103: Rails for Zombies Slides Spanish

Añadimos autorización

Page 104: Rails for Zombies Slides Spanish

Añadimos autorización

Page 105: Rails for Zombies Slides Spanish

Petición

/app/controllers/tweets_controller.rb

class TweetsController < ApplicationController

end

Acciones Controller

def show

def index

Vistadef edit

def create

def update

def destroy

def new

Listar todos los tweetsMostrar un tweetFormulario de nuevo tweetFormulario para editar tweetCrear nuevo tweetActualizar tweetBorrar tweet

Page 106: Rails for Zombies Slides Spanish

Petición

/app/controllers/tweets_controller.rb

class TweetsController < ApplicationController

end

Before Filters

Vistadef edit

def update

def destroy

Formulario para editar tweet

Actualizar tweetBorrar tweet

Necesitan autorización

Page 107: Rails for Zombies Slides Spanish

Petición

/app/controllers/tweets_controller.rb

class TweetsController < ApplicationController

end

def edit

def update

def destroy

@tweet = Tweet.find(params[:id])

end

@tweet = Tweet.find(params[:id])

@tweet = Tweet.find(params[:id])

end

end...

...

...

Before Filters

Page 108: Rails for Zombies Slides Spanish

Petición

/app/controllers/tweets_controller.rb

class TweetsController < ApplicationController

end

def edit

def update

def destroy

@tweet = Tweet.find(params[:id])

end

@tweet = Tweet.find(params[:id])@tweet = Tweet.find(params[:id])

end

end...

...

...

def get_tweet

end

before_filter :get_tweet, :only => [:edit, :update, :destroy]

Before Filters

Page 109: Rails for Zombies Slides Spanish

Petición

/app/controllers/tweets_controller.rb

class TweetsController < ApplicationController

end

def editdef updatedef destroy

@tweet = Tweet.find(params[:id])def get_tweet

end

before_filter :get_tweet, :only => [:edit, :update, :destroy]

if session[:zombie_id] != @tweet.zombie_idflash[:notice] = "Sorry, you can’t edit this tweet"redirect_to tweets_path

end

def check_auth

end

before_filter :check_auth, :only => [:edit, :update, :destroy]

Before Filters

Page 110: Rails for Zombies Slides Spanish

Añadimos autorización

Page 111: Rails for Zombies Slides Spanish

PrÁCTICA ZOMBI 4PRÁCTICA ZOMBI 4

Page 112: Rails for Zombies Slides Spanish

Una introduccion a RailsEpisodio #5

Thiscontentisavailablefreeonh1p://RailsForZombies.org

created by

Page 113: Rails for Zombies Slides Spanish

Episodio #5Enrutando en la oscuridad

Page 114: Rails for Zombies Slides Spanish

Nuestro Application Stack

4 Componentes

Views

Models

Controllers

Routing

Page 115: Rails for Zombies Slides Spanish

Para poder encontrar estas rutas

Action Code The URL Generated

List all tweets tweets_path /tweetsNew tweet form new_tweet_path /tweets/new

Action Code The URL Generated

Show a tweet tweet /tweets/1

Edit a tweet edit_tweet_path(tweet) /tweets/1/edit

Delete a tweet tweet, :method => :delete /tweets/1

tweet = Tweet.find(1) Estas rutas necesitan un tweet

<%= link_to "<link text>", <code> %>

Page 116: Rails for Zombies Slides Spanish

Petición

/app/controllers/tweets_controller.rb

class TweetsController < ApplicationController

end

def show

def index

Vistadef edit

def create

def update

def destroy

def new

Listar todos los tweetsMostrar un tweetFormulario de nuevo tweetFormulario para editar tweetCrear tweetActualizar un tweetBorrar un teet

y estas acciones

Page 117: Rails for Zombies Slides Spanish

Necesitamos definir rutas

ZombieTwitter::Application.routes.draw do |map|resources :tweets

end

Código URL generada Acción TweetsController

tweets_path /tweets def indextweet /tweet/<id> def shownew_tweet_path /tweets/new def newedit_tweet_path(tweet) /tweets/<id>/edit def edity algunas mas...

Crea lo que llamamosun recurso “REST”ful

zombie_twitter

config

routes.rb

Page 118: Rails for Zombies Slides Spanish

ZombieTwitter::Application.routes.draw do |map|resources :tweets

end

/config/routes.rb

Rutas customhttp://localhost:3000/new_tweet http://localhost:3000/tweets/new

class TweetsController

end

def new

end...

Nombre Controller Tweets

Nombre Acción new

match 'new_tweet' => "Tweets#new"

Controller AcciónRuta

renderiza

Page 119: Rails for Zombies Slides Spanish
Page 120: Rails for Zombies Slides Spanish

Named Routes

match 'all' => "Tweets#index"

<%= link_to "All Tweets",? %>

tweets_path no funcionaría

http://localhost:3000/all http://localhost:3000/tweets

class TweetsController

end

def index

end...

Nombre Controller Tweets

Nombre Acción index

renderiza

Page 121: Rails for Zombies Slides Spanish

match 'all' => "Tweets#index"

<%= link_to "All Tweets", %>

, :as => "all_tweets"

all_tweets_path

http://localhost:3000/all http://localhost:3000/tweets

class TweetsController

end

def index

end...

renderizaNamed Routes

Nombre Controller Tweets

Nombre Acción index

Page 122: Rails for Zombies Slides Spanish
Page 123: Rails for Zombies Slides Spanish

redirige a

Page 124: Rails for Zombies Slides Spanish
Page 125: Rails for Zombies Slides Spanish

Redirect

match 'all' => redirect('/tweets')

match 'google' => redirect('http://www.google.com/')

http://localhost:3000/all http://localhost:3000/tweetsredirige a

Page 126: Rails for Zombies Slides Spanish

Ruta raíz

root :to => "Tweets#index"

<%= link_to "All Tweets", %>root_path

Controller Acción

http://localhost:3000/ http://localhost:3000/tweetsrenderiza

Page 127: Rails for Zombies Slides Spanish

/app/controllers/tweets_controller.rb

Parámetros en rutas/local_tweets/32828 Muestra todos lo

s

tweets en este código

postal/local_tweets/32801

if params[:zipcode]@tweets = Tweet.where(:zipcode => params[:zipcode])

else @tweets = Tweet.allend

respond_to do |format| format.html # index.html.erb format.xml { render :xml => @tweets } end end

def index

Page 128: Rails for Zombies Slides Spanish

referenciado como params[:zipcode] en el controller

match 'local_tweets/:zipcode' => 'Tweets#index'

match 'local_tweets/:zipcode' => 'Tweets#index', :as => 'local_tweets'

<%= link_to "Tweets in 32828", local_tweets_path(32828) %>

Parámetros en rutas/local_tweets/32828 Muestra todos lo

s

tweets en este código

postal/local_tweets/32801

Page 129: Rails for Zombies Slides Spanish
Page 130: Rails for Zombies Slides Spanish
Page 131: Rails for Zombies Slides Spanish

/app/controllers/tweets_controller.rb

/github/greggpollack

match ':name' => 'Tweets#index', :as => 'zombie_tweets'

Muestra los tweets de estos zombies

<%= link_to "Gregg", zombie_tweets_path('greggpollack') %>

/eallam/envylabs

def index if params[:name] @zombie = Zombie.where(:name => params[:name]).first @tweets = @zombie.tweets else @tweets = Tweet.all end end

Parámetros en rutas

Page 132: Rails for Zombies Slides Spanish
Page 133: Rails for Zombies Slides Spanish

PRÁCTICA ZOMBI 5PRÁCTICA ZOMBI 5

Page 134: Rails for Zombies Slides Spanish

Thiscontentisavailablefreeonh1p://RailsForZombies.org

created by

Page 135: Rails for Zombies Slides Spanish

name author URL

Toothless Zombie Ateo Fiel http://www.flickr.com/photos/ateofiel/292853829/

Still Eating Brains? SanFranAnnie http://www.flickr.com/photos/sanfranannie/4557247098/

brains! ginnerobot http://www.flickr.com/photos/ginnerobot/2978178952/

Blue Eyed Zombie Josh Jensen http://www.flickr.com/photos/jwjensen/3919674567/

zombie puberty zenobia_joy http://www.flickr.com/photos/zenobia_joy/4006626151/

Zombie March Chicago Eric Ingrum http://www.flickr.com/photos/ericingrum/2600434956/

construction sign underbiteman http://www.flickr.com/photos/underbiteman/2638246638/

ZombieWalk Asbury Park Bob Jagendorf http://www.flickr.com/photos/bobjagendorf/3978792454/

gravestone2_5416 doviende http://www.flickr.com/photos/doviende/38013223

Creative Commons