SlideShare une entreprise Scribd logo
1  sur  40
Télécharger pour lire hors ligne
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

Contenu connexe

En vedette

Rails Text Mate Cheats
Rails Text Mate CheatsRails Text Mate Cheats
Rails Text Mate Cheats
dezarrolla
 
Rails 3 generators
Rails 3 generatorsRails 3 generators
Rails 3 generators
joshsmoore
 
Railsguide
RailsguideRailsguide
Railsguide
lanlau
 
Introducing Command Line Applications with Ruby
Introducing Command Line Applications with RubyIntroducing Command Line Applications with Ruby
Introducing Command Line Applications with Ruby
Nikhil Mungel
 

En vedette (11)

Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104
 
Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1
 
Rails01
Rails01Rails01
Rails01
 
Rest and Rails
Rest and RailsRest and Rails
Rest and Rails
 
Rails Text Mate Cheats
Rails Text Mate CheatsRails Text Mate Cheats
Rails Text Mate Cheats
 
Rails 3 generators
Rails 3 generatorsRails 3 generators
Rails 3 generators
 
Railsguide
RailsguideRailsguide
Railsguide
 
Rails 3 Beginner to Builder 2011 Week 3
Rails 3 Beginner to Builder 2011 Week 3Rails 3 Beginner to Builder 2011 Week 3
Rails 3 Beginner to Builder 2011 Week 3
 
Introducing Command Line Applications with Ruby
Introducing Command Line Applications with RubyIntroducing Command Line Applications with Ruby
Introducing Command Line Applications with Ruby
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
 
Ruby on Rails for beginners
Ruby on Rails for beginnersRuby on Rails for beginners
Ruby on Rails for beginners
 

Similaire à Ruby on Rails 101

Magento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with MagentoMagento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
MagentoImagine
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHP
smueller_sandsmedia
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
Michelangelo van Dam
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)
Ivan Chepurnyi
 

Similaire à Ruby on Rails 101 (20)

Implementing Quality on Java projects
Implementing Quality on Java projectsImplementing Quality on Java projects
Implementing Quality on Java projects
 
잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with MagentoMagento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
 
Magento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with MagentoMagento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHP
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfast
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripe
 
Ant, Maven and Jenkins
Ant, Maven and JenkinsAnt, Maven and Jenkins
Ant, Maven and Jenkins
 
Puppet At Twitter - Puppet Camp Silicon Valley
Puppet At Twitter - Puppet Camp Silicon ValleyPuppet At Twitter - Puppet Camp Silicon Valley
Puppet At Twitter - Puppet Camp Silicon Valley
 
Vtlib 1.1
Vtlib 1.1Vtlib 1.1
Vtlib 1.1
 
Object identification and its management
Object identification and its managementObject identification and its management
Object identification and its management
 
Property Based Testing in PHP
Property Based Testing in PHPProperty Based Testing in PHP
Property Based Testing in PHP
 
Implement rich snippets in your webshop
Implement rich snippets in your webshopImplement rich snippets in your webshop
Implement rich snippets in your webshop
 
Tips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxTips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptx
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)
 
Writing maintainable Oracle PL/SQL code
Writing maintainable Oracle PL/SQL codeWriting maintainable Oracle PL/SQL code
Writing maintainable Oracle PL/SQL code
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

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