• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Ruby on Rails 101
 

Ruby on Rails 101

on

  • 2,218 views

Ruby on Rails 101 as presented by Clayton Lengel-Zigich at Desert Code Camp on April 2nd, 2011

Ruby on Rails 101 as presented by Clayton Lengel-Zigich at Desert Code Camp on April 2nd, 2011

Statistics

Views

Total Views
2,218
Views on SlideShare
2,013
Embed Views
205

Actions

Likes
1
Downloads
14
Comments
0

6 Embeds 205

http://www.claytonlz.com 192
http://tiesandtutus.com 5
http://new.claytonlz.com 3
http://feeds2.feedburner.com 2
http://feeds.feedburner.com 2
http://www.pennyauctionedge.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Ruby on Rails 101 Ruby on Rails 101 Presentation Transcript

    • 101 1.9.2 Ruby on 3.0.5 Rails @claytonlz - Desert Code Camp 2011.1 - http://spkr8.com/t/7007Saturday, April 2, 2011
    • Ecosystem Models Controllers Views Deploying & Optimizing Resources for LearningSaturday, April 2, 2011
    • CommunitySaturday, April 2, 2011
    • “This sure is a nice fork, I bet I could… HOLY SHIT A KNIFE!”Saturday, April 2, 2011
    • OpinionatedSaturday, 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
    • RapidDevelopmentSaturday, 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 LearningSaturday, April 2, 2011
    • Models Associations Validations Callbacks QueryingSaturday, April 2, 2011
    • Models ActiveRecord::Base class Product < ActiveRecord::Base ... products end name string sku string price decimalSaturday, 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 manufacturersSaturday, 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 products 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, "Cant be active if its been recalled") end endSaturday, 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!").allSaturday, 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 ConventionsSaturday, 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.xmlSaturday, 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/ endSaturday, 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}") endSaturday, 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_productSaturday, 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 endSaturday, April 2, 2011
    • Views Layouts & Helpers Forms Partials ActionView HelpersSaturday, 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 SanitizeHelperSaturday, April 2, 2011
    • Deploying & Optimizing Heroku Passenger NewRelicSaturday, April 2, 2011
    • Resources for Learning Video PeepCode RailsCasts CodeSchool Books The Rails Way Beginning Ruby Ruby for _________ Other PHX Rails User Group GangplankSaturday, April 2, 2011
    • @claytonlz http://spkr8.com/t/7007Saturday, April 2, 2011