SlideShare a Scribd company logo
101
     1.9.2

             Ruby
             on
                          3.0.5
             Rails

          @claytonlz - Desert Code Camp 2011.1 - http://spkr8.com/t/7007




Saturday, April 2, 2011
Ecosystem
                  Models
                  Controllers
                  Views
                  Deploying & Optimizing
                  Resources for Learning


Saturday, April 2, 2011
Community

Saturday, April 2, 2011
“This sure is a nice fork,
                           I bet I could… HOLY
                             SHIT A KNIFE!”




Saturday, April 2, 2011
Opinionated

Saturday, April 2, 2011
“I flippin’ told you MVC
                           is the only way to build
                           web apps! Teach you to
                                 doubt DHH!”




Saturday, April 2, 2011
Rapid
Development
Saturday, April 2, 2011
“These goats are okay,
                           but I really need a yak
                          for some quality shaving”




Saturday, April 2, 2011
Ecosystem
                  Models
                  Controllers
                  Views
                  Deploying
                  Resources for Learning


Saturday, April 2, 2011
Models

                  Associations
                  Validations
                  Callbacks
                  Querying




Saturday, April 2, 2011
Models



         ActiveRecord::Base
       class Product < ActiveRecord::Base
         ...                                products
       end
                                            name    string


                                             sku    string


                                            price   decimal




Saturday, April 2, 2011
Models ➤ Associations
       # manufacturer                                       ingredients
       has_many   :products

       # product
       has_one            :upc
       belongs_to         :manufacturer
       has_many           :batches                batches
       has_many           :ingredients,
                          :through => :batches

       # batch
       belongs_to :product                                    products
       belongs_to :ingredient

       # ingredient
       has_many :batches
       has_many :products,
                :through => :batches               upcs     manufacturers




Saturday, April 2, 2011
Models ➤ Associations

       # create a product and find its manufacturer
       product = manufacturer.products.create({:name => "Kitlifter"})
       product.manufacturer

       # create a upc and find its product's manufacturer
       upc = product.create_upc({:code => "001122"})
       upc.product.manufacturer

       # create a batch (linking a product and ingredient)
       wheat = Ingredient.create({:name => "Wheat"})
       bread = Product.create({:name => "Bread"})

       batch.create({:product => bread, :ingredient => wheat})




Saturday, April 2, 2011
Models ➤ Associations


                                          When should I use has_one
                                          and belongs_to?



                          “Using has_many or belongs_to is more than
                          just on which table the foreign key is placed,
                            itʼs a matter of who can be thought of as
                          ʻowningʼ the other. A product ʻownsʼ a UPC.”




Saturday, April 2, 2011
Models ➤ Validations

     class Product < ActiveRecord::Base
       validates_presence_of   :name
       validates_uniqueness_of :name
       validates_format_of     :sku, :with => /^SKUd{8}$/
       validates_inclusion_of :usda_rating, :in => %w( prime choice )

          validate :cannot_be_active_if_recalled

       def cannot_be_active_if_recalled
         if recalled? && recalled_on < Date.today
         errors.add(:active, "Can't be active if it's been recalled")
       end
     end




Saturday, April 2, 2011
Models ➤ Validations

                                     I know my record is
                                     technically invalid, but
                                     I want to save it anyhow.



                          “It is possible to save a record,
                             without validating, by using
                            save(:validate => false)”




Saturday, April 2, 2011
Models ➤ Callbacks

   class Ingredient
                                                             Callback
        before_destroy    :determine_destroyability           Chain
        before_create     :format_legacy_name
        after_update      :log_changes
        after_create      :import_harvest_data
                                                      determine_destroyability
        #    validation
        #    create
        #    save
        #    update
        #    destroy

   end
                                                        STOP!!




Saturday, April 2, 2011
Models ➤ Querying

       Product.find(98)
       Product.find_by_name("Diet Coke")
       Product.find_by_name_and_sku("Diet Coke", "SKU44387")
       Product.find([98,11,39])
       Product.first
       Product.last
       Product.all
       Product.count

       # old and busted
       Product.find(:all, :conditions => {:name => "Cheese-it!"})

       # new hotness
       Product.where(:name => "Cheese-it!").all




Saturday, April 2, 2011
Models ➤ Querying
       Product.where("name = ?", 'Skittles')
       Product.where(:created_at => Date.yesterday..Date.today)
       Product.where(:sku => ["SKU912", "SKU187", "SKU577"])

       Product.order('name DESC')

       Product.select('id, name')

       Product.limit(5)

       # chainable
       Product.where(:created_at => Date.yesterday..Date.today)
              .limit(10)

       Product.order('created_at ASC').limit(20).offset(40)

       Product.select('created_at').where(:name => 'Twix')




Saturday, April 2, 2011
Models ➤ Querying
     manufacturer.includes(:products)
                 .where('products.usda_rating = ?', 'prime')

     manufacturer.includes(:products)
                 .where(:state => 'AZ')
                 .order('created_at')

     manufacturer.includes(:products => :ingredients)
                 .where('ingredients.name = ?', 'glucose')
                 .order('updated_at')

     manufacturer.joins(:products)
                 .where('products.sku = ?', 'SKU456')

     ingredient.includes(:products => {:manufacturer => :conglomerate})
               .where('conglomerates.name = ?', 'nestle')

     animalia.includes(:phylum => {:class => {:order => {:family => :genus}}})

     child.includes(:parent => [:brother, {:sister => :children}])




Saturday, April 2, 2011
Models ➤ Validations


                                      Why would I use joins
                                      instead of includes?



                             “Using includes will load the
                          records into memory when the query
                              is executing, joins will not.”




Saturday, April 2, 2011
Controllers

                  Routing
                  Filters
                  Conventions




Saturday, April 2, 2011
Controllers ➤ Routing
      resources :products
      # GET /products            =>   index action
      # GET /products/new        =>   new action
      # GET /products/:id        =>   show action
      # GET /products/:id/edit   =>   edit action
      #
      # POST /products           => create action
      #
      # PUT /products/:id        => update action
      #
      # DELETE /products/:id     => destroy action

      products_path # /products
      products_url # http://www.example.com/products

      product_path(@product) # /products/29
      product_path(@product, :xml) # /products/29.xml




Saturday, April 2, 2011
Controllers ➤ Routing
      namespace :admin do
        resources :users
        resources :orders
      end

      admin_users_path # /admin/users
      edit_admin_order_path # /admin/orders/4/edit

      class Admin::UsersController < ApplicationController
        # /app/controllers/admin/users_controller.rb
        # /app/views/admin/users/
      end




Saturday, April 2, 2011
Controllers ➤ Routing
    resources :accounts, :except => :destroy do
      resources :users do
        post :activate, :on => :member
        collection do
          get 'newest'
        end
      end

      resources :clients, :only => [:index, :show]
    end

    account_users_path(@account) # /accounts/182/users
    newest_account_users_path(@account) # /accounts/182/users/newest
    activate_account_user_path(@account, @user) # /accounts/182/user/941

    accounts_clients_path(@account) # /accounts/182/clients
    new_accounts_client_path(@account) # FAIL!




Saturday, April 2, 2011
Controllers ➤ Filters
    class UsersController < ApplicationController
      before_filter :load_manufacturer
      before_filter :find_geo_data, :only => [:show]
      skip_before_filter :require_login

      after_filter :log_access
    end

    # in ApplicationController
    def log_access
      Rails.logger.info("[Access Log] Users Controller access at #{Time.now}")
    end




Saturday, April 2, 2011
Controllers ➤ Conventions
          class ProductsController < ApplicationController
            def index
              # GET /products
            end                                              def update
             def show
               # GET /products/:id
             end
                                                         ☹     # ... update occurred
                                                               @parent.children.each ...
                                                             end
             def new
               # GET /products/new
             end
                                                      def edit
             def create                                 @product = Product.find(params[:id])
               # POST /products                       end


                                               ☹
             end
                                                      def show
             def edit                                   @product = Product.find(params[:id])
               # GET /products/:id/edit
                                                      end
             end
                                                      def destroy
             def update
               # PUT /products/:id                      @product = Product.find(params[:id])
             end                                      end

            def destroy
              # DELETE /products/:id
            end
          end
                                              ☺       before_filter :load_product




Saturday, April 2, 2011
Controllers ➤ Conventions
          class ProductsController < ApplicationController
            def index
              # GET /products
            end
                                                               def update

                                                           ☹
             def show
               # GET /products/:id
                                                                 # ... update occurred
               # renders /app/views/products/show.format         @parent.children.each ...
             end                                               end
             def new
               # GET /products/new
             end
                                                       def edit
             def create                                  @product = Product.find(params[:id])
               # POST /products                        end


                                                ☹
               redirect_to products_url
             end                                       def show
                                                         @product = Product.find(params[:id])
             def edit
                                                       end
               # GET /products/:id/edit
             end
                                                       def destroy
             def update                                  @product = Product.find(params[:id])
               # PUT /products/:id                     end
             end

            def destroy
              # DELETE /products/:id
            end
                                               ☺       before_filter :load_product


          end




Saturday, April 2, 2011
Views

                  Layouts & Helpers
                  Forms
                  Partials
                  ActionView Helpers




Saturday, April 2, 2011
Views ➤ Layouts & Helpers

     def show
       @product = Product.find(params[:id])
     end                                      M   C
     <!-- app/views/products/show.html.erb -->
     <h2><%= @product.name %></h2>

                                                  V
     <p>Price: <%= @product.price %></p>

     <!-- app/layouts/application.html.erb -->
     <div id="container">
       <%= yield %>
     </div>

     <div id="container">
       <h2>Pop-Tarts</h2>
       <p>Price: $3.99</p>
     </div>




Saturday, April 2, 2011
Views ➤ Layouts & Helpers
 <h2><%= @product.name %></h2>
 <p>Price: <%= number_to_currency(@product.price) %></p>
 <p>Ingredients: <%= @product.ingredients.present? ? @product.ingredients.map(&:name).join(',') : 'N/A' %></p>




 # app/helpers/products_helper.rb
 def display_ingredients(ingredients)
   return "N/A" if ingredients.blank?
   ingredients.map(&:name).join(',')
 end



 <h2><%= @product.name %></h2>
 <p>Price: <%= number_to_currency(@product.price) %></p>
 <p>Ingredients: <%= display_ingredients(@product.ingredients) %></p>




Saturday, April 2, 2011
Views ➤ Forms
      <%= form_tag search_path do %>
        <p>
          <%= text_field_tag 'q' %><br />
          <%= submit_tag('Search') %>
        </p>
      <% end %>

      <form action="/search" method="post">
        <p>
          <input type="text" name="q" value="" id="q" />
          <input type="submit" name="commit_search" value="Search" id="commit_search" />
        </p>
      </form>




Saturday, April 2, 2011
Views ➤ Forms
     <h2>New Product</h2>
     <%= form_for(@product) do |f| %>
       <!-- action => /products/:id -->
       <!-- method => POST -->
                                           ← New Record
       <p>
         <%= f.text_field :name %>
       </p>
       <p>
         <%= f.check_box :active %>       <h2>Edit Product</h2>
       </p>                               <%= form_for(@product) do |f| %>
     <% end %>                              <!-- action => /products/:id -->
                                            <!-- method => PUT -->

                                            <p>
                                              <%= f.text_field :name %>
               Existing Record →            </p>
                                            <p>
                                              <%= f.check_box :active %>
                                            </p>
                                          <% end %>




Saturday, April 2, 2011
Views ➤ Forms

      <%=       f.hidden_field :secret %>
      <%=       f.password_field :password %>
      <%=       f.label :name, "Product Name" %>
      <%=       f.radio_button :style, 'Clear' %>
      <%=       f.text_area, :description %>
      <%=       f.select :condition, ["Good", "Fair", "Bad"] %>

      <%= f.email_field :user_email %>
      <%= f.telephone_field :cell_number %>




Saturday, April 2, 2011
Views ➤ Partials
      <% @products.each do |product| %>
        <tr><td><%= link_to(product.title, product_path(product)) %></td></tr>
      <% end %>

      <% @products.each do |product| %>
        <%= render :partial => 'product_row', :locals => {:product => product} %>
      <% end %>



      <!-- app/views/products/_product_row.html.erb -->
      <tr><td><%= link_to(product.title, product_path(product)) %></td></tr>

      <%= render :partial => 'product_row', :collection => @products, :as => :product %>




Saturday, April 2, 2011
Views ➤ Partials
      <!-- app/views/shared/_recent_changes.html.erb -->
      <ul>
        <li>...</li>
        <li>...</li>
      </ul>

      <!-- app/views/reports/index.html.erb -->
      <%= render :partial => 'shared/recent_changes' %>

      <!-- app/views/pages/news.html.erb -->
      <%= render :partial => 'shared/recent_changes' %>



      <%= render :partial => @product %>
      <%= render(@product) %>

      <%= render 'bio', :person => @john   %>




Saturday, April 2, 2011
Views ➤ Partials

                  NumberHelper
                  TextHelper
                  FormHelper
                  JavaScriptHelper
                  DateHelper
                  UrlHelper
                  CaptureHelper
                  SanitizeHelper




Saturday, April 2, 2011
Deploying & Optimizing



                  Heroku
                  Passenger
                  NewRelic

Saturday, April 2, 2011
Resources for Learning
                  Video
                          PeepCode
                          RailsCasts
                          CodeSchool
                  Books
                          The Rails Way
                          Beginning Ruby
                    Ruby for _________
                  Other
                          PHX Rails User Group
                          Gangplank



Saturday, April 2, 2011
@claytonlz
   http://spkr8.com/t/7007

Saturday, April 2, 2011

More Related Content

PDF
Sql Antipatterns Strike Back
PDF
International News | World News
PDF
Technology and Science News - ABC News
PDF
What Would You Do? With John Quinones
PDF
Technology and Science News - ABC News
PDF
Technology and Science News - ABC News
PDF
Nashville Symfony Functional Testing
PDF
Unit testing with zend framework tek11
Sql Antipatterns Strike Back
International News | World News
Technology and Science News - ABC News
What Would You Do? With John Quinones
Technology and Science News - ABC News
Technology and Science News - ABC News
Nashville Symfony Functional Testing
Unit testing with zend framework tek11

Viewers also liked (11)

PDF
Ruby on Rails Kickstart 103 & 104
KEY
Ruby on Rails Training - Module 1
PDF
PPTX
Rest and Rails
PDF
Rails Text Mate Cheats
KEY
Rails 3 generators
PDF
Railsguide
PDF
Rails 3 Beginner to Builder 2011 Week 3
KEY
Introducing Command Line Applications with Ruby
PDF
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
PDF
Ruby on Rails for beginners
Ruby on Rails Kickstart 103 & 104
Ruby on Rails Training - Module 1
Rest and Rails
Rails Text Mate Cheats
Rails 3 generators
Railsguide
Rails 3 Beginner to Builder 2011 Week 3
Introducing Command Line Applications with Ruby
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails for beginners
Ad

Similar to Ruby on Rails 101 (20)

PDF
Implementing Quality on Java projects
PDF
잘 알려지지 않은 Php 코드 활용하기
KEY
Workshop quality assurance for php projects tek12
PDF
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
PDF
Magento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
PDF
international PHP2011_ilia alshanetsky_Hidden Features of PHP
PDF
Workshop quality assurance for php projects - phpbelfast
PDF
Workshop quality assurance for php projects - ZendCon 2013
PDF
Quality Assurance for PHP projects - ZendCon 2012
PDF
Unit Testing in SilverStripe
PDF
Ant, Maven and Jenkins
PPTX
Puppet At Twitter - Puppet Camp Silicon Valley
PDF
Vtlib 1.1
PPTX
Object identification and its management
PDF
Property Based Testing in PHP
PDF
Implement rich snippets in your webshop
PPTX
Tips On Trick Odoo Add-On.pptx
PDF
Getting Started with Selenium
PPTX
Making Magento flying like a rocket! (A set of valuable tips for developers)
PPT
Writing Maintainable Code
Implementing Quality on Java projects
잘 알려지지 않은 Php 코드 활용하기
Workshop quality assurance for php projects tek12
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
international PHP2011_ilia alshanetsky_Hidden Features of PHP
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - ZendCon 2013
Quality Assurance for PHP projects - ZendCon 2012
Unit Testing in SilverStripe
Ant, Maven and Jenkins
Puppet At Twitter - Puppet Camp Silicon Valley
Vtlib 1.1
Object identification and its management
Property Based Testing in PHP
Implement rich snippets in your webshop
Tips On Trick Odoo Add-On.pptx
Getting Started with Selenium
Making Magento flying like a rocket! (A set of valuable tips for developers)
Writing Maintainable Code
Ad

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
PPTX
Big Data Technologies - Introduction.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Spectroscopy.pptx food analysis technology
PDF
Machine learning based COVID-19 study performance prediction
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Cloud computing and distributed systems.
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
sap open course for s4hana steps from ECC to s4
Approach and Philosophy of On baking technology
Big Data Technologies - Introduction.pptx
Chapter 3 Spatial Domain Image Processing.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Electronic commerce courselecture one. Pdf
Review of recent advances in non-invasive hemoglobin estimation
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Spectroscopy.pptx food analysis technology
Machine learning based COVID-19 study performance prediction
Diabetes mellitus diagnosis method based random forest with bat algorithm
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
“AI and Expert System Decision Support & Business Intelligence Systems”
Network Security Unit 5.pdf for BCA BBA.
Dropbox Q2 2025 Financial Results & Investor Presentation
Encapsulation_ Review paper, used for researhc scholars
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Cloud computing and distributed systems.
Understanding_Digital_Forensics_Presentation.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
sap open course for s4hana steps from ECC to s4

Ruby on Rails 101

  • 1. 101 1.9.2 Ruby on 3.0.5 Rails @claytonlz - Desert Code Camp 2011.1 - http://spkr8.com/t/7007 Saturday, April 2, 2011
  • 2. Ecosystem Models Controllers Views Deploying & Optimizing Resources for Learning Saturday, April 2, 2011
  • 4. “This sure is a nice fork, I bet I could… HOLY SHIT A KNIFE!” Saturday, April 2, 2011
  • 6. “I flippin’ told you MVC is the only way to build web apps! Teach you to doubt DHH!” Saturday, April 2, 2011
  • 8. “These goats are okay, but I really need a yak for some quality shaving” Saturday, April 2, 2011
  • 9. Ecosystem Models Controllers Views Deploying Resources for Learning Saturday, April 2, 2011
  • 10. Models Associations Validations Callbacks Querying Saturday, April 2, 2011
  • 11. Models ActiveRecord::Base class Product < ActiveRecord::Base ... products end name string sku string price decimal Saturday, April 2, 2011
  • 12. Models ➤ Associations # manufacturer ingredients has_many :products # product has_one :upc belongs_to :manufacturer has_many :batches batches has_many :ingredients, :through => :batches # batch belongs_to :product products belongs_to :ingredient # ingredient has_many :batches has_many :products, :through => :batches upcs manufacturers Saturday, April 2, 2011
  • 13. Models ➤ Associations # create a product and find its manufacturer product = manufacturer.products.create({:name => "Kitlifter"}) product.manufacturer # create a upc and find its product's manufacturer upc = product.create_upc({:code => "001122"}) upc.product.manufacturer # create a batch (linking a product and ingredient) wheat = Ingredient.create({:name => "Wheat"}) bread = Product.create({:name => "Bread"}) batch.create({:product => bread, :ingredient => wheat}) Saturday, April 2, 2011
  • 14. Models ➤ Associations When should I use has_one and belongs_to? “Using has_many or belongs_to is more than just on which table the foreign key is placed, itʼs a matter of who can be thought of as ʻowningʼ the other. A product ʻownsʼ a UPC.” Saturday, April 2, 2011
  • 15. Models ➤ Validations class Product < ActiveRecord::Base validates_presence_of :name validates_uniqueness_of :name validates_format_of :sku, :with => /^SKUd{8}$/ validates_inclusion_of :usda_rating, :in => %w( prime choice ) validate :cannot_be_active_if_recalled def cannot_be_active_if_recalled if recalled? && recalled_on < Date.today errors.add(:active, "Can't be active if it's been recalled") end end Saturday, April 2, 2011
  • 16. Models ➤ Validations I know my record is technically invalid, but I want to save it anyhow. “It is possible to save a record, without validating, by using save(:validate => false)” Saturday, April 2, 2011
  • 17. Models ➤ Callbacks class Ingredient Callback before_destroy :determine_destroyability Chain before_create :format_legacy_name after_update :log_changes after_create :import_harvest_data determine_destroyability # validation # create # save # update # destroy end STOP!! Saturday, April 2, 2011
  • 18. Models ➤ Querying Product.find(98) Product.find_by_name("Diet Coke") Product.find_by_name_and_sku("Diet Coke", "SKU44387") Product.find([98,11,39]) Product.first Product.last Product.all Product.count # old and busted Product.find(:all, :conditions => {:name => "Cheese-it!"}) # new hotness Product.where(:name => "Cheese-it!").all Saturday, April 2, 2011
  • 19. Models ➤ Querying Product.where("name = ?", 'Skittles') Product.where(:created_at => Date.yesterday..Date.today) Product.where(:sku => ["SKU912", "SKU187", "SKU577"]) Product.order('name DESC') Product.select('id, name') Product.limit(5) # chainable Product.where(:created_at => Date.yesterday..Date.today) .limit(10) Product.order('created_at ASC').limit(20).offset(40) Product.select('created_at').where(:name => 'Twix') Saturday, April 2, 2011
  • 20. Models ➤ Querying manufacturer.includes(:products) .where('products.usda_rating = ?', 'prime') manufacturer.includes(:products) .where(:state => 'AZ') .order('created_at') manufacturer.includes(:products => :ingredients) .where('ingredients.name = ?', 'glucose') .order('updated_at') manufacturer.joins(:products) .where('products.sku = ?', 'SKU456') ingredient.includes(:products => {:manufacturer => :conglomerate}) .where('conglomerates.name = ?', 'nestle') animalia.includes(:phylum => {:class => {:order => {:family => :genus}}}) child.includes(:parent => [:brother, {:sister => :children}]) Saturday, April 2, 2011
  • 21. Models ➤ Validations Why would I use joins instead of includes? “Using includes will load the records into memory when the query is executing, joins will not.” Saturday, April 2, 2011
  • 22. Controllers Routing Filters Conventions Saturday, April 2, 2011
  • 23. Controllers ➤ Routing resources :products # GET /products => index action # GET /products/new => new action # GET /products/:id => show action # GET /products/:id/edit => edit action # # POST /products => create action # # PUT /products/:id => update action # # DELETE /products/:id => destroy action products_path # /products products_url # http://www.example.com/products product_path(@product) # /products/29 product_path(@product, :xml) # /products/29.xml Saturday, April 2, 2011
  • 24. Controllers ➤ Routing namespace :admin do resources :users resources :orders end admin_users_path # /admin/users edit_admin_order_path # /admin/orders/4/edit class Admin::UsersController < ApplicationController # /app/controllers/admin/users_controller.rb # /app/views/admin/users/ end Saturday, April 2, 2011
  • 25. Controllers ➤ Routing resources :accounts, :except => :destroy do resources :users do post :activate, :on => :member collection do get 'newest' end end resources :clients, :only => [:index, :show] end account_users_path(@account) # /accounts/182/users newest_account_users_path(@account) # /accounts/182/users/newest activate_account_user_path(@account, @user) # /accounts/182/user/941 accounts_clients_path(@account) # /accounts/182/clients new_accounts_client_path(@account) # FAIL! Saturday, April 2, 2011
  • 26. Controllers ➤ Filters class UsersController < ApplicationController before_filter :load_manufacturer before_filter :find_geo_data, :only => [:show] skip_before_filter :require_login after_filter :log_access end # in ApplicationController def log_access Rails.logger.info("[Access Log] Users Controller access at #{Time.now}") end Saturday, April 2, 2011
  • 27. Controllers ➤ Conventions class ProductsController < ApplicationController def index # GET /products end def update def show # GET /products/:id end ☹ # ... update occurred @parent.children.each ... end def new # GET /products/new end def edit def create @product = Product.find(params[:id]) # POST /products end ☹ end def show def edit @product = Product.find(params[:id]) # GET /products/:id/edit end end def destroy def update # PUT /products/:id @product = Product.find(params[:id]) end end def destroy # DELETE /products/:id end end ☺ before_filter :load_product Saturday, April 2, 2011
  • 28. Controllers ➤ Conventions class ProductsController < ApplicationController def index # GET /products end def update ☹ def show # GET /products/:id # ... update occurred # renders /app/views/products/show.format @parent.children.each ... end end def new # GET /products/new end def edit def create @product = Product.find(params[:id]) # POST /products end ☹ redirect_to products_url end def show @product = Product.find(params[:id]) def edit end # GET /products/:id/edit end def destroy def update @product = Product.find(params[:id]) # PUT /products/:id end end def destroy # DELETE /products/:id end ☺ before_filter :load_product end Saturday, April 2, 2011
  • 29. Views Layouts & Helpers Forms Partials ActionView Helpers Saturday, April 2, 2011
  • 30. Views ➤ Layouts & Helpers def show @product = Product.find(params[:id]) end M C <!-- app/views/products/show.html.erb --> <h2><%= @product.name %></h2> V <p>Price: <%= @product.price %></p> <!-- app/layouts/application.html.erb --> <div id="container"> <%= yield %> </div> <div id="container"> <h2>Pop-Tarts</h2> <p>Price: $3.99</p> </div> Saturday, April 2, 2011
  • 31. Views ➤ Layouts & Helpers <h2><%= @product.name %></h2> <p>Price: <%= number_to_currency(@product.price) %></p> <p>Ingredients: <%= @product.ingredients.present? ? @product.ingredients.map(&:name).join(',') : 'N/A' %></p> # app/helpers/products_helper.rb def display_ingredients(ingredients) return "N/A" if ingredients.blank? ingredients.map(&:name).join(',') end <h2><%= @product.name %></h2> <p>Price: <%= number_to_currency(@product.price) %></p> <p>Ingredients: <%= display_ingredients(@product.ingredients) %></p> Saturday, April 2, 2011
  • 32. Views ➤ Forms <%= form_tag search_path do %> <p> <%= text_field_tag 'q' %><br /> <%= submit_tag('Search') %> </p> <% end %> <form action="/search" method="post"> <p> <input type="text" name="q" value="" id="q" /> <input type="submit" name="commit_search" value="Search" id="commit_search" /> </p> </form> Saturday, April 2, 2011
  • 33. Views ➤ Forms <h2>New Product</h2> <%= form_for(@product) do |f| %> <!-- action => /products/:id --> <!-- method => POST --> ← New Record <p> <%= f.text_field :name %> </p> <p> <%= f.check_box :active %> <h2>Edit Product</h2> </p> <%= form_for(@product) do |f| %> <% end %> <!-- action => /products/:id --> <!-- method => PUT --> <p> <%= f.text_field :name %> Existing Record → </p> <p> <%= f.check_box :active %> </p> <% end %> Saturday, April 2, 2011
  • 34. Views ➤ Forms <%= f.hidden_field :secret %> <%= f.password_field :password %> <%= f.label :name, "Product Name" %> <%= f.radio_button :style, 'Clear' %> <%= f.text_area, :description %> <%= f.select :condition, ["Good", "Fair", "Bad"] %> <%= f.email_field :user_email %> <%= f.telephone_field :cell_number %> Saturday, April 2, 2011
  • 35. Views ➤ Partials <% @products.each do |product| %> <tr><td><%= link_to(product.title, product_path(product)) %></td></tr> <% end %> <% @products.each do |product| %> <%= render :partial => 'product_row', :locals => {:product => product} %> <% end %> <!-- app/views/products/_product_row.html.erb --> <tr><td><%= link_to(product.title, product_path(product)) %></td></tr> <%= render :partial => 'product_row', :collection => @products, :as => :product %> Saturday, April 2, 2011
  • 36. Views ➤ Partials <!-- app/views/shared/_recent_changes.html.erb --> <ul> <li>...</li> <li>...</li> </ul> <!-- app/views/reports/index.html.erb --> <%= render :partial => 'shared/recent_changes' %> <!-- app/views/pages/news.html.erb --> <%= render :partial => 'shared/recent_changes' %> <%= render :partial => @product %> <%= render(@product) %> <%= render 'bio', :person => @john %> Saturday, April 2, 2011
  • 37. Views ➤ Partials NumberHelper TextHelper FormHelper JavaScriptHelper DateHelper UrlHelper CaptureHelper SanitizeHelper Saturday, April 2, 2011
  • 38. Deploying & Optimizing Heroku Passenger NewRelic Saturday, April 2, 2011
  • 39. Resources for Learning Video PeepCode RailsCasts CodeSchool Books The Rails Way Beginning Ruby Ruby for _________ Other PHX Rails User Group Gangplank Saturday, April 2, 2011
  • 40. @claytonlz http://spkr8.com/t/7007 Saturday, April 2, 2011