Riding the Rails
controladoras, vistas y modelos
MVC
1
    6    Controladora

                            5
     2
          3             4



Modelo                      Vis...
ActionView




        ActionPack + ActionController




                ActiveRecord




MySQL   MSSql      Oracle      M...
Modelos
ActiveRecord
Person               People

       new               id   name     age
       find
     destroy             1...
ActiveRecord




 id
        todos los modelos
        enteros
        TODOS los modelos
No apto
para DBAs
Person People
Data Datum
Animal Animals
ActiveRecord
             new
           create
             find
          destroy
      update_attributes
             sa...
ActiveRecord
Modelo.new
 hace una instancia del modelo


Modelo.create
 hace una instancia del modelo, la graba y
 retorna...
ActiveRecord


Modelo. nd(id)
Modelo. nd_by_atributo

Modelo. nd_by_atributo_a
nd_atributo_and_atributo_
and_atributo
Method Missing


def method_missing(method,*args)

end
def method_missing(method,*args)
 super unless method ~= /$find_by_(/A*)/
 # obtienen atributos
 fields = fields.split(“_and_...
Validaciones
validates_presence_of
                :attributo


validates_acceptance_of
                 :terms
validates_length_of
                 :name,
                :maximun => 6
                :minimun => 2

validates_uniquen...
def validate
 #lógica compleja
end
Grabando modelo
 .valid?
           validations
           validate


 .save
Controladoras
class UsersController < ApplicationController
end

           ProductsController
           PagesController
           Ses...
class UsersController < ApplicationController

 def index

 end

 def show

 end

 def new

 end

 def create

 end

 def ...
class UsersController < ApplicationController

 def index

 end

 def show

 end

 def setup

 end

 def start

 end

end
class UsersController < ApplicationController

 def index

 end

 def show

 end

 private

    def setup

    end

    de...
@instancias
  van directamente a la vista

   def home

    @issues = Issue.all

   end
Before, After, Around

before_ lter :accion
after_ lter :accion
around_ lter :accion
around_ lter :accion
 def action
     @log = Logger.new
     @log.message = “Cargando”
     @log.save
      yield
     @lo...
Before, After, Around

before_ lter :accion, :only => :create
before_ lter :accion, :except
=> :create
before_ lter :accio...
Cookies y Sesiones
session[:user] = User.find(1)
cookie[:remember_me_time] = 30.days
demo
Agregando un sistema
  de autenticación
    en 5 minutos
00:05min
      Requerimos usuarios
                         modelo




generador   elemento a            columna:tipo
    ...
00:20min
   Migramos el cambio a
     la base de datos


create_table(:users)
00:40min
Agregamos uno
00:54min
Ahora debemos
crear una sesión
controladora




generador   elemento a                  acciones a crear
              generar




                      ...
:controller=>”session”, :action=>”new”




 SessionController


:action=>”create”
class SessionController < ApplicationController

 def login
  @user = User.new
 end

 def create
  @user = User.new(params...
views/session/login.html.erb
                                               cambiamos la url
                             ...
Creamos dos métodos en la controladora
padre

app/controllers/application_controller.rb

                                 ...
El ltro ejecutará el método antes de usar
otras acciones en la controladora




                             03:41min
¡Y listo!

04:20min
RR01-06 Introducción a Ruby y Rails
Upcoming SlideShare
Loading in...5
×

RR01-06 Introducción a Ruby y Rails

1,103

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,103
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
16
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide














































  • RR01-06 Introducción a Ruby y Rails

    1. 1. Riding the Rails controladoras, vistas y modelos
    2. 2. MVC
    3. 3. 1 6 Controladora 5 2 3 4 Modelo Vista
    4. 4. ActionView ActionPack + ActionController ActiveRecord MySQL MSSql Oracle MongoDB API
    5. 5. Modelos
    6. 6. ActiveRecord Person People new id name age find destroy 1 Alvaro 24 update_attributes save 2 Andrés 21 3 Carmen 56
    7. 7. ActiveRecord id todos los modelos enteros TODOS los modelos
    8. 8. No apto para DBAs
    9. 9. Person People Data Datum Animal Animals
    10. 10. ActiveRecord new create find destroy update_attributes save valid? new_record?
    11. 11. ActiveRecord Modelo.new hace una instancia del modelo Modelo.create hace una instancia del modelo, la graba y retorna. Tiene un id creado
    12. 12. ActiveRecord Modelo. nd(id)
    13. 13. Modelo. nd_by_atributo Modelo. nd_by_atributo_a nd_atributo_and_atributo_ and_atributo
    14. 14. Method Missing def method_missing(method,*args) end
    15. 15. def method_missing(method,*args) super unless method ~= /$find_by_(/A*)/ # obtienen atributos fields = fields.split(“_and_”) # merge fields = args.merge(fields) self.class_eval “ def #{method}(args) find(:all,:conditions=>fields,args) end #{method}(args) “ end
    16. 16. Validaciones
    17. 17. validates_presence_of :attributo validates_acceptance_of :terms
    18. 18. validates_length_of :name, :maximun => 6 :minimun => 2 validates_uniqueness_of :identi er
    19. 19. def validate #lógica compleja end
    20. 20. Grabando modelo .valid? validations validate .save
    21. 21. Controladoras
    22. 22. class UsersController < ApplicationController end ProductsController PagesController SessionController
    23. 23. class UsersController < ApplicationController def index end def show end def new end def create end def edit end def edit end def destroy end end
    24. 24. class UsersController < ApplicationController def index end def show end def setup end def start end end
    25. 25. class UsersController < ApplicationController def index end def show end private def setup end def start end end
    26. 26. @instancias van directamente a la vista def home @issues = Issue.all end
    27. 27. Before, After, Around before_ lter :accion after_ lter :accion around_ lter :accion
    28. 28. around_ lter :accion def action @log = Logger.new @log.message = “Cargando” @log.save yield @log.message = “Cargó!” @log.save end
    29. 29. Before, After, Around before_ lter :accion, :only => :create before_ lter :accion, :except => :create before_ lter :accion, :only => [:create, :new, :edit]
    30. 30. Cookies y Sesiones
    31. 31. session[:user] = User.find(1)
    32. 32. cookie[:remember_me_time] = 30.days
    33. 33. demo
    34. 34. Agregando un sistema de autenticación en 5 minutos
    35. 35. 00:05min Requerimos usuarios modelo generador elemento a columna:tipo generar
    36. 36. 00:20min Migramos el cambio a la base de datos create_table(:users)
    37. 37. 00:40min Agregamos uno
    38. 38. 00:54min Ahora debemos crear una sesión
    39. 39. controladora generador elemento a acciones a crear generar 01:15min
    40. 40. :controller=>”session”, :action=>”new” SessionController :action=>”create”
    41. 41. class SessionController < ApplicationController def login @user = User.new end def create @user = User.new(params[:user]) @db_user = User.find_by_email_and_password(@user.email,@user.password) if @db_user session[:current_user] = @db_user.id flash[:notice] = "Bienvenido #{@db_user.email}" if session[:last_url] redirect_to session[:last_url] else redirect_to root_path end else session[:current_user] = nil flash[:error] = "Datos inválidos" render :action => :login end end def destroy session[:current_user] = nil redirect_to root_path end end 02:15min
    42. 42. views/session/login.html.erb cambiamos la url por default <%= flash[:error] %> <% form_for @user, :url=>{:action=>"create"} do |f| %> <%= f.label :email %> <%= f.text_field :email %> <br /> <%= f.label :password %> <%= f.password_field :password %> <%= f.submit "Iniciar sesion" %> <% end %> 02:48min
    43. 43. Creamos dos métodos en la controladora padre app/controllers/application_controller.rb si no está log ueado, lo manda a la vista “login” de “Session” def logged_only unless logged_in? session[:last_url] = request.url redirect_to url_for(:controller=>"session",:action=>"login") end end def logged_in? session[:current_user] end 03:16min
    44. 44. El ltro ejecutará el método antes de usar otras acciones en la controladora 03:41min
    45. 45. ¡Y listo! 04:20min
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×