Está en la página 1de 135

Thiscontentisavailablefreeon h1p://RailsForZombies.

org

created by

Una introduccion a Rails Episodio #1

Thiscontentisavailablefreeon h1p://RailsForZombies.org

created by

Requisitos:

TryRuby.org

Episodio #1

A fondo en el CRUD

PARA ZOM BI S!!

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

Serie de pares clave valor

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

zombie Ash Bob Jim Ash

CRUD

DESAFO ZOMBI #1 RESPUESTA t

Obten un hash del tweet con id = 3


= Tweet.find(3) 3
"I just ate some delicious brains."

puts t[:id] puts t[:status] puts t[:zombie]

"Jim"

CRUD
t = Tweet.find(3) puts t[:id]

puts t.id

a Igu la

puts t[:status] puts t[:zombie]

puts t.status puts t.zombie

RESPUESTA puts

t.id

3
"I just ate some delicious brains."

puts t.status puts t.zombie

"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 Crear Read Leer Update Actualizar Delete Borrar

Create

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

Read

Tweet.find(3)

Update

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

Delete

t = Tweet.find(3) t.destroy

Create
t = Tweet.new t.status = "I <3 t.zombie = "Jim" t.save

Sintaxis

Sintaxis alternativa

l e s o m a n g i s a e o t n n e e m u a q brains." c i t n e m o s t o u a j a i F a n g i s . a s o e r t S o s o . n d i por

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

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

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

Tweet.where(:zombie => "ash")

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

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

Una introduccion a Rails Episodio #2

Thiscontentisavailablefreeon h1p://RailsForZombies.org

created by

Episodio #2 Los Modelos saben a pollo

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

zombie Ash Bob Jim Ash

Tweet
app/models/tweet.rb
class Tweet < ActiveRecord::Base end

MODELOS

tweets
id 1 2 3 4

Asocia la clase a la tabla


zombie Ash Bob Jim Ash

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

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


validates_presence_of :status end
> t = Tweet.new

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

o t u b i r t A

n i c a Valid

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

VALIDACIO NE

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

S E N O I C A L E R

Porque siempre viajan en manadas

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

5 Your eyelids taste like bacon.

zombies
id 1 2 3 Ash Bob Jim

name

graveyard Glen Haven Memorial Cemetery Chapel Hill Cemetery My Fathers Basement

A Tweet belongs to a Zombie


app/models/tweet.rb
class Tweet < ActiveRecord::Base belongs_to :zombie end

A Zombie has many Tweets


app/models/zombie.rb
class Zombie < ActiveRecord::Base has_many :tweets end

r a l u g n i 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

A Tweet belongs to a Zombie

> 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

Una introduccion a Rails Episodio #3

Thiscontentisavailablefreeon h1p://RailsForZombies.org

created by

Episodio #3 La vista no siempre es bonita


Me voy a comer su cerebrito

Nuestro Application Stack

VISTAS

Views

Models

4 Componentes

Edible Rotting Bodies


zombie_twitter app views zombies tweets

VISTAS

Embedded Ruby
Ruby empotrado en HTML

Listar todos los tweets Ver un tweet

index.html.erb show.html.erb

Mostrar un tweet
<% ... %>

Evaluar Ruby

<%= ... %>

Eval. e imprimir resultado

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

TO, ESTE CDIGO HUELE MAL...


(por 2 razones)

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

<%= yield %>


</body></html>

/app/views/tweets/show.html.erb
<% tweet = Tweet.find(1) %> <h1><%= tweet.status %></h1> <p>Posted by <%= tweet.zombie.name %></p>

zombie_twitter app views layouts zombies tweets

VISTAS

La plantilla principal

application.html.erb

Listar todos los tweets Ver un tweet

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

<%= yield %>


</body></html>

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

<%= yield %>


</body></html>

Componentes adicionales
<%= stylesheet_link_tag :all %>

Incluye

zombie_twitter public stylesheets

todas las hoj as de est ilo

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

<%= javascript_include_tag :defaults %>

<%= csrf_meta_tag %>

Componentes adicionales
<%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %>

zombie_twitter public javascripts

Incluye los JS por de fecto

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>

Frame work Javas de cript Proto type

<%= csrf_meta_tag %>

Componentes adicionales
<%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> <%= csrf_meta_tag %>

SITIO Hacker Zombi

ite.co <form target="http://yours

m">

Renderiza

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

P . ej. sp am de coment arios

Tu web

Esto es aadido automticamente a los formularios

Ruta raz e imgenes


http://ZombieTwitter.com/[algo]
zombie_twitter public stylesheets javascripts images

c i l b u p / s l n i e a R e t s i a x e a v i S o n i s , a s u se

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

Aadir un enlace
/app/views/tweets/show.html.erb
... <p>Posted by <%= tweet.zombie.name %></p>

l a r a z a l n E

i b zom
%>

<%= link_to tweet.zombie.name , zombie_path(tweet.zombie)

Texto enlace Ruta enlace (URL)

Renderiza

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

Tambin se puede escribir as


<%= link_to tweet.zombie.name, tweet.zombie %>

Texto enlace

Objeto a mostrar

Mtodo

link_to

? r a s u o d e u p s e n o i c p o Qu

1. Mira el cdigo fuente


Lnea de comando

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

Abre tu editor y busca por def link_to

Mtodo

link_to

? r a s u o d e u p s e n o i c p o u Q

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

http://api.rubyonrails.org

Mtodo

link_to

? r a s u o d e u p s e n o i c p o u Q

3. API Dock
(documentacin online de Ruby y Rails)

http://apidock.com/rails

Mtodo

link_to

? r a s u o d e u p s e n o i c p o Qu
(local y online)

4. Rails Searchable API Doc


http://railsapi.com/

http://railsapi.com/

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

zombie_twitter app views layouts zombies tweets

VISTAS

La plantilla principal

application.html.erb

Listar todos los tweets Ver un tweet

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>

Tweet.all array de tweets


tweet

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

V Tabla vaca? ISTAS

<% Tweet.all.each do |tweet| %> <tr> <td><%= link_to tweet.status, tweet %></td> <td><%= link_to tweet.zombie.name, tweet.zombie %></td> </tr> <% end %>

V Tabla vaca? ISTAS

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

V Tabla vaca? ISTAS

<% tweets = Tweet.all %> <% ... <% end %> .each do |tweet| %>

V Tabla vaca? ISTAS

<% tweets = Tweet.all %> <% tweets.each do |tweet| %> ... <% end %>

<% if tweets.size == 0 %> <em>No tweets found</em> <% end %>

V Tabla vacia? ISTAS

<% tweets = Tweet.all %> <% tweets.each do |tweet| %> ... <% end %>

<% if tweets.empty? %> <em>No tweets found</em> <% end %>

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> <td><%= link_to "Edit", edit_tweet_path(tweet) %></td> <td><%= link_to "Delete", tweet, :method => :delete %></td> </tr> <% end %>

Todos los enlaces para tweets


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

Accin

Cdigo

URL generada

List all tweets New tweet form

tweets_path new_tweet_path

/tweets /tweets/new

tweet = Tweet.find(1)
Accin Cdigo

Estas rutas necesi tan un tweet


URL generada

Show a tweet Edit a tweet Delete a tweet

tweet edit_tweet_path(tweet)

/tweets/1 /tweets/1/edit

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

PRCTICA ZOMBI 3

Una introduccion a Rails Episodio #4

Thiscontentisavailablefreeon h1p://RailsForZombies.org

created by

Episodio #4 e c v Los controllers se comen

s o r reb

Nuestro Application Stack

Views Controllers Models 4 Componentes

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>

TO, ESTE CDIGO HUELE MAL...


(lo arreglamos luego)

zombie_twitter app controllers tweets_controller.rb /app/controllers/tweets_controller.rb

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>

zombie_twitter app controllers tweets_controller.rb tweets /app/controllers/tweets_controller.rb

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>

QU PASA CON LAS VARIABLES?

Variable de instancia
@
/app/controllers/tweets_controller.rb
def show @ tweet = Tweet.find(1) end end

Peticin
/tweets/1

class TweetsController < ApplicationController

/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

class TweetsController < ApplicationController

/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

class TweetsController < ApplicationController

/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]

class TweetsController < ApplicationController

/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

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

params = {:tweet => { :status => "Im dead" }}


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

Tambin lo podemos escribir as


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

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

class TweetsController < ApplicationController

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

zombie_twitter app views tweets edit.html.erb

Aadimos autorizacin

Aadimos autorizacin

Aadimos autorizacin

Redirect y Flash
/app/controllers/tweets_controller.rb
def edit @tweet = Tweet.find(params[:id])

Peticin

class TweetsController < ApplicationController

if session[:zombie_id] != @tweet.zombie_id flash[:notice] = "Sorry, you cant edit this tweet" redirect_to(tweets_path) end end end

session flash[:notice] redirect_to <ruta>

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

class TweetsController < ApplicationController

if session[:zombie_id] != @tweet.zombie_id redirect_to(tweets_path , :notice => "Sorry, you cant edit this tweet") end end end

Sintaxis alternativa combinando redirect & flash

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

<%= yield %>


</body></html>

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

<%= yield %>


</body></html>

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

class TweetsController < ApplicationController

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

class TweetsController < ApplicationController

def edit

Formulario para editar tweet Actualizar tweet Borrar tweet

Vista

def update def destroy end

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

PrCTICA ZOMBI 4 PRCTICA

Una introduccion a Rails Episodio #5

Thiscontentisavailablefreeon h1p://RailsForZombies.org

created by

Episodio #5

Enrutando en la oscuridad

Nuestro Application Stack

Routing Views Controllers Models 4 Componentes

Para poder encontrar estas rutas


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

Action

Code

The URL Generated

List all tweets New tweet form

tweets_path new_tweet_path

/tweets /tweets/new

tweet = Tweet.find(1)
Action Code

Estas rutas necesi tan un tweet


The URL Generated

Show a tweet Edit a tweet Delete a tweet

tweet edit_tweet_path(tweet)

/tweets/1 /tweets/1/edit

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

y estas acciones
/app/controllers/tweets_controller.rb
def index def show def new def edit def create def update def destroy end

Peticin

class TweetsController < ApplicationController

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

Necesitamos denir rutas


Crea lo q ue llamam os un recurso RESTful

routes.rb

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


Cdigo URL generada Accin TweetsController def index def show def new def edit

tweets_path tweet new_tweet_path edit_tweet_path(tweet) y algunas mas...

/tweets /tweet/<id> /tweets/new /tweets/<id>/edit

Rutas custom

http://localhost:3000/new_tweet

renderiza http://localhost:3000/tweets/new
class TweetsController def new ... end end

Nombre Controller Tweets Nombre Accin new

/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

Nombre Controller Tweets Nombre Accin index

class TweetsController def index ... end end

match 'all' => "Tweets#index"

<%= link_to "All Tweets",

tweets_path no funcionara

%>

Named Routes
http://localhost:3000/all

renderiza

http://localhost:3000/tweets

Nombre Controller Tweets Nombre Accin index

class TweetsController def index ... end end

, :as => "all_tweets" match 'all' => "Tweets#index"

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

redirige a

Redirect
http://localhost:3000/all

redirige a

http://localhost:3000/tweets

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

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

Ruta raz
http://localhost:3000/

renderiza

http://localhost:3000/tweets

root :to => "Tweets#index"

Controller

Accin

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

Parmetros en rutas
/local_tweets/32828 /local_tweets/32801

s o l s o d o t a r t s Mue o g i d c e t s e n e s t e e w t postal

/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

s o l s o d o t a r t s Mue o g i d c e t s e n e s t e e w t postal

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

referenciado como params[:zipcode] en el controller


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

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

Parmetros en rutas
/github /greggpollack /eallam /envylabs

e d s t e e w t s lo a r t s Mue estos zombies

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

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

/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

ZombieWalk Asbury Park Bob Jagendorf gravestone2_5416 doviende

También podría gustarte