SlideShare uma empresa Scribd logo
1 de 10
Baixar para ler offline
Migrations                                                                                                           1 of 10



To Create a Blank Migration: rails g migration <name>
To Add Columns: rails g migration Add<Anything>To<TableName> [columnName:type]
To Remove Columns: rails g migration Remove<Anything>From<TableName> [columnName:type]



Column Options                          Migration Methods*                        Active Record Supported Types
 default:           <value>              create_table         change_table         :primary_key         :string
 limit:             30                   drop_table           add_column           :text                :integer
 null:              false                change_column        rename_column        :float               :decimal
 first:             true                 remove_column        add_index            :datetime            :timestamp
 after:             :email               remove_index                              :time                :date
 unique:            true                                                           :binary              :boolean

                                         * See documentation for syntax


Remove Column                                                 Add Column
 rails g migration RemoveAgeFromZombies age:integer            rails g migration AddEmailToZombies email:string


 class RemoveAgeFromZombies < ActiveRecord::Migration          class AddEmailToZombies < ActiveRecord::Migration
   def up                                                        def up
     remove_column :zombies, :age                                  add_column :zombies, :email, :string
   end                                                           end
   def down                                                      def down
     add_column :zombies, :age, :integer                           remove_column :zombies, :email
   end                                                           end
 end                                                           end


Create Table                                                                      Don’t Forget to Rake!
 rails g migration CreateZombiesTable name:string, bio:text, age:integer           $ rake db:migrate
                                                                                   Run all missing migrations
 class CreateZombiesTable < ActiveRecord::Migration
                                                                                   $ rake db:rollback
   def up
                                                                                   Rollback the previous migration
     create_table :zombies do |t|
       t.string :name                                                              $ rake db:setup
       t.text :bio                                                                 Create db, load schema & seed
       t.integer :age
                                                                                   $ rake db:schema:dump
       t.timestamps
                                                                                   Dump the current db state
     end
   end
                                                                                              db/schema.rb
   def down
     drop_table :zombies
   end
 end


Resources:
http://guides.rubyonrails.org/migrations.html
Rails Command Line                                                                                                 2 of 10




Command                Shortcut        Description
 rails new <app name>			                 # creates a new Rails application

 rails server		          rails s		       # starts up the Rails server

 rails generate		        rails g		       # generates template code
                                                                                     Help:
 rails console		         rails c		       # starts up the Rails console               All commands can be run with -h
                                                                                     for more information
 rails dbconsole		       rails db	       # starts up the Rails db console


Generate Examples
 rails g scaffold zombie name:string bio:text age:integer

 rails g migration RemoveEmailFromUser email:string

 rails g mailer ZombieMailer decomp_change lost_brain




Models
Named Scope                                                   Examples
 class Zombie < ActiveRecord::Base                              Zombie.rotting
   scope :rotting, where(rotting: true)                         Zombie.fresh
   scope :fresh, where(“age < 20”)                              Zombie.recent
   scope :recent, order(“created_at desc”).limit(3)             Zombie.rotting.recent
 end


Callbacks                                         Examples
 before_validation        after_validation            after_create :send_welcome_email
 before_save              after_save                  before_save :encrypt_password
 before_create            after_create                before_destroy :set_deleted_flag
 before_update            after_update                after_update {|zombie| logger.info “Zombie #{zombie.id} updated” }
 before_destroy           after_destroy


Self Scope                                                    Relationship Options
Reading attributes does not require “self ” but setting
                                                                dependent: :destroy
attributes does require “self ”
                                                                foreign_key: :undead_id
                                                                primary_key: :zid
                                                                validate: true
 class Zombie < ActiveRecord::Base
   before_save :make_rotting
   def make_rotting                                           Relational Includes Examples*
     if age > 20
       self.rotting = true                                      @zombies = Zombie.includes(:brain).all
     end                                                        @recent = Zombie.recent.includes(:brain)
   end
                                                               * To avoid extra queries
 end
REST & Routes                                                                                                        3 of 10




Rake Routes                       Generates
 $ rake routes                     zombies       GET /zombies              {:action=>”index”, :controller=>”zombies”}
                                                 POST /zombies             {:action=>”create”, :controller=>”zombies”}
- Prints your RESTful routes       new_zombie    GET /zombies/new          {:action=>”new”, :controller=>”zombies”}
                                   edit_zombie   GET /zombies/:id/edit     {:action=>”edit”, :controller=>”zombies”}
                                   zombie        GET /zombies/:id          {:action=>”show”, :controller=>”zombies”}
                                                 PUT /zombies/:id          {:action=>”update”, :controller=>”zombies”}
                                                 DELETE /zombies/:id       {:action=>”destroy”, :controller=>”zombies”}


Example Link To Usage                                           Relative Paths       Path Generated
 <%=   link_to   'All Zombies', zombies_path %>                  zombies_path        /zombies
 <%=   link_to   'New Zombie', new_zombie_path %>                new_zombie_path     /zombies/new
 <%=   link_to   'Edit Zombie', edit_zombie_path(@zombie) %>
 <%=   link_to   'Show Zombie', zombie_path(@zombie) %>         Absolute Paths       URL Generated
 <%=   link_to   'Show Zombie', @zombie %>
 <%=   link_to   'Delete Zombie', @zombie, method :delete %>     zombies_url         http://localhost:3000/zombies
                                                                 new_zombie_url      http://localhost:3000/zombies/new




Forms
Example                                                                            Alternate Text Input Helpers
 <%= form_for(@zombie) do |f| %>                                                     <%=   f.password_field :password %>
   <%= f.text_field :name %>                                                         <%=   f.number_field :price %>
   <%= f.text_area :bio %>                                                           <%=   f.range_field :quantity %>
                                                                                     <%=   f.email_field :email %>
   <%= f.select :decomp, ['fresh', 'rotting', 'stale'] %>                            <%=   f.url_field :website %>
   <%= f.select :decomp, [['fresh', 1], ['rotting', 2], ['stale', 3]] %>             <%=   f.telephone_field :mobile %>

   <%= f.radio_button :decomp, 'fresh', checked: true %>
   <%= f.radio_button :decomp, 'rotting' %>
   <%= f.radio_button :decomp, 'stale' %>

   <%= f.check_box :rotting %>

   <%= f.submit %>
 <% end %>
Nested Routes                                                                                              4 of 10




1   app/configure/routes.rb
     TwitterForZombies::Application.routes.draw do
       resources :zombies do
         resources :tweets
       end
     end




2   app/controller/tweets_controller.rb
     class TweetsController < ApplicationController
       before_filter :get_zombie

       def get_zombie
         @zombie = Zombie.find(params[:zombie_id])
       end

       def show
                                                                  /zombies/4/tweets/2
         @tweet = @zombie.tweets.find(params[:id])
                                                                  params = { :zombie_id => 4, :id => 2 }
       end

       def create
         @tweet = @zombie.tweets.new(params[:tweet])
         if @tweet.save
           redirect_to [@zombie, @tweet]
         else
           render action: “new”
       end

       def index
                                                                  /zombies/4/tweets
         @tweets = @zombie.tweets
                                                                  params = { :zombie_id => 4 }
       end
     end




3   app/views/tweets/_form.html.erb
     <%= form_for([@zombie, @tweet]) do |f| %>




4   app/views/tweets/index.html.erb
     <% @tweets.each do |tweet| %>
       <tr>
                                                                                     Look Up URL Helpers
                                                                                      $ rake routes

         <td><%= tweet.body %></td>
         <td><%= link_to ‘Show’, [@zombie, tweet] %></td>
         <td><%= link_to ‘Edit’, edit_zombie_tweet_path(@zombie, tweet) %></td>
         <td><%= link_to ‘Destroy’, [@zombie, tweet], method: :delete %></td>
       </tr>
     <% end %>

     <%= link_to ‘New Tweet’, new_zombie_tweet_path(@zombie) %>
View Partials & View Helpers                                                                                               5 of 10




app/views/tweets/new.html.erb
 <h1>New tweet</h1>
 <%= render 'form' %>                                         app/views/tweets/_form.html.erb
 <%= link_to 'Back', zombie_tweets_path(@zombie) %>
                                                               <h1>New tweet</h1>
                                                               <%= render 'form' %>
app/views/tweets/edit.html.erb
                                                               <%= link_to 'Back', zombie_tweets_path(@zombie) %>
 <h1>Editing tweet</h1>
 <%= render 'form' %>                                          - Partials start with an underscore




View Helper                                              Same As                          Calls
 <div id="tweet_<%= tweet.id %>" class="tweet">       <%= div_for tweet do %>           dom_id(@tweet)    ->   #tweet_2
   <%= tweet.body %>                                    <%= tweet.body %>
 </div>                                               <% end %>


View Helper                                              Same As                          Looks For
 <%= @zombies.each do |zombie| %>                     <%= render @zombies %>            views/zombies/_zombie.html.erb
   <%= render zombie %>
 <% end %>




Additional Helpers                                                                 Result
 <%= truncate("I need brains!", :length => 10) %>                                   I need bra…


 <%= truncate("I need brains!", :length => 10, :separator => ' ') %>                I need…


 I see <%= pluralize(Zombie.count, "zombie") %>                                     I see 2 zombies / I see 1 zombie


 His name was <%= @zombie.name.titleize %>                                          His name was Ash Williams


 Ash’s zombie roles are <%= @role_names.to_sentence %>                              Ash’s zombie roles are Captain, and Solidier.


 He was buried alive <%= time_ago_in_words @zombie.created_at %> ago                He was buried alive 2 days ago


 Price is <%= number_to_currency 13.5 %>                                            Price is $13.50


 Ash is <%= number_to_human 13234355423 %> years old %>                             Ash is 13.2 billion years old
Creating a Mailer                                                                                                6 of 10



Generator: rails g mailer ZombieMailer decomp_change lost_brain


Mailer Class Example -    app/mailers/zombie_mailer.rb                     Additional Options
 class ZombieMailer < ActionMailer::Base                                    from: my@email.com
   default from: "from@example.com"                                         cc: my@email.com
                                                                            bcc: my@email.com
   def decomp_change(zombie)                                                reply_to: my@email.com
     @zombie = zombie
     @last_tweet = @zombie.tweets.last                                     Mass Mailing Notes:
                                                                           Mass mailing is best done outside of
     attachments['z.pdf'] = File.read("#{Rails.root}/public/zombie.pdf")
                                                                           Rails. You can use gems for services
     mail to: @zombie.email, subject: 'Your decomp stage has changed'
                                                                           like MadMimi.com if you plan on
   end
                                                                           sending a lot of mail.
 end


Mailer Text Views -   app/views/zombie_mailer/decomp_change.text.erb       Resources:
                                                                           http://guides.rubyonrails.org/action_
 Greetings <%= @zombie.name %>                                             mailer_basics.html

Mailer HTML Views -     app/views/zombie_mailer/decomp_change.html.erb

 <h1>Greetings <%= @zombie.name %></h1>


Sending Mail -   app/models/zombie.rb

 ZombieMailer.decomp_change(@zombie).deliver




Assets & Asset Paths
Asset Tag Helpers
 <%= javascript_include_tag "custom" %>


 <%= stylesheet_link_tag "style" %>


 <%= image_tag "rails.png" %>


Asset Paths in Stylesheets -     app/assets/stylesheets/zombie.css.erb

 form.new_zombie input.submit {
   background-image: url(<%= asset_path('button.png') %>);
 }


Using SASS, CoffeeScript Assets
To compile with other CSS/JS helpers, just add the necessary extension.
                                                                           Resources:
                                                                           http://sass-lang.org
 app/assets/stylesheets/zombie.css.scss.erb
                                                                           http://jashkenas.github.com/coffee-script/
 app/assets/javascripts/zombies.js.coffee
CoffeeScript & jQuery                                                                                                       7 of 10




JavaScript & jQuery                                       CoffeeScript & jQuery
app/assets/javascripts/zombie.js                          app/assets/javascripts/zombie.js.coffee

 $(document).ready(function() {                          $(document).ready ->
   $('#show-bio').click(function(event) {                  $('#show-bio').click (event) ->
     event.preventDefault();                                 event.preventDefault()
     $(this).hide();                                         $(this).hide()
     $('.field#bio').show();                                 $('.field#bio').show()
   }
 }


CoffeeScript AJAX Example
 $(document).ready ->
   $('div#custom_phase2 form').submit (event) ->
     event.preventDefault()
     url = $(this).attr('action')
     custom_decomp = $('div#custom_phase2 #zombie_decomp').val()

       $.ajax
         type: 'put'
         url: url
         data: { zombie: { decomp: custom_decomp } }
         dataType: 'json'
         success: (json) ->
           $('#decomp').text(json.decomp).effect('highlight')
           $('div#custom_phase2').fadeOut() if json.decomp == "Dead (again)"




SASS & CSS
CSS                                                                 SASS
app/assets/stylesheets/zombie.css.erb                               app/assets/stylesheets/zombie.css.scss.erb

 form.new_zombie {                                                 form.new_zombie {
   border: 1px dashed gray;                                          border: 1px dashed gray;
 }
                                                                       .field#bio {
 form.new_zombie .field#bio {                                            display: none;
   display: none;                                                      }
 }
                                                                       input.submit {
 form.new_zombie input.submit {                                            background-image: url(<%= asset_path('button.png') %>);
     background-image: url(<%= asset_path('button.png') %>);           }
 }                                                                 }



To Remove SASS/CoffeeScript Default Asset Generation
             Gemfile

              gem 'sass-rails'
Remove                                       then rerun 'bundle install'
              gem 'coffee-script'
Sprockets & Application.js/.css                                                                                              8 of 10




app/assets/javascripts/application.js
Contains a manifest of the JavaScript files we use


 //= require jquery                                            Looks for jquery.js in all asset paths
 //= require jquery_ujs

 //= require shared                                            Loads: lib/assets/javascripts/shared.js.coffee

 //= require_tree .




app/assets/stylesheet/application.css
Contains a manifest of the stylesheets we use


 /*
  *= require reset
  *= require_self                                              Styles in this file are included after the reset stylesheet
  *= require_tree .
  */

 form.new_zombie {
   border: 1px dashed gray;
 }




Rendering / HTTP Status Codes
Responds_to Example
app/controllers/zombies_controller.rb

 class ZombiesController < ApplicationController
   def show
     @zombie = Zombie.find(params[:id])
     respond_to do |format|
       format.html do
         if @zombie.decomp == 'Dead (again)'
            render :dead_again                                 Renders app/views/zombies/dead_again.html.erb
         end
                                                               Renders app/views/zombies/show.html.erb
       end
       format.json { render json: @zombie }                    Renders JSON
     end
   end
 end


HTTP Status Codes                                  JSON Rendering Examples
 200 :ok                   401 :unauthorized         render json: @zombie.errors, status: :unprocessable_entity
 201 :created              102 :processing           render json: @zombie, status: :created, location: @zombie
 422 :unprocessed_entity   404 :not_found
Custom Routes                                                                                                     9 of 10




Types                                   Route                                     URL
 :member                                 get :decomp, on: :member                  /zombies/:id/decomp
 acts on a single resource
                                         put :decay, on: :member                   /zombies/:id/decay
 :collection
 acts on a collection of resources
                                         get :fresh, on: :collection               /zombies/fresh


                                         post :search, on: :collection             /zombies/search


                                        Examples
                                         <%=   link_to 'Fresh zombies', fresh_zombies_path %>
                                         <%=   form_tag(search_zombies_path) do |f| %>
                                         <%=   link_to 'Get decomp', decomp_zombie_path(@zombie) %>
                                         <%=   form_for @zombie, url: decay_zombie_path(@zombie) %>




Custom JSON Responses
Examples
 @zombie.to_json(only: :name)            @zombie.to_json(except: [:created_at, :updated_at, :id, :email, :bio])


 { “name” : “Eric” }                     { "age":25, "decomp":"Fresh", "name":"Eric", "rotting":false }




 @zombie.to_json(only: [:name, :age])    @zombie.to_json(include: :brain, except: [:created_at, :updated_at, :id])


 { “name” : “Eric”, "age": 25 }          {
                                             "age":25,
                                             "bio":"I am zombified",
                                             "decomp":"Fresh",
                                             "email":"zom@bied.com",
                                             "name":"Eric",
                                             "rotting":false,
                                             "brain": { "flavor":"Butter", "status":"Smashed", "zombie_id":3 }
                                         }
AJAX                                                                                          10 of 10




1   Make a Remote Link or Form Call
     <%= link_to 'delete', zombie, method: :delete, remote: true %>


     <a href="/zombies/5" data-method="delete" data-remote="true" rel="nofollow">delete</a>



     <%= form_for (@zombie, remote: true) do |f| %>


     <form action="/zombies" data-remote="true" method="post">




2   Ensure the Controller Can Accept JavaScript Calls
     respond_to do |format|
       format.js
     end




3   Write the JavaScript to Return to the Client
    app/views/zombies/<action name>.js.erb


     $('#<%= dom_id(@zombie) %>').fadeOut();



    Other jQuery Actions
     $('<selector>').append(<content or jQuery object>);
     $('<selector>').effect('highlight');                         Requires jQuery UI
     $('<selector>').text(<string>);

Mais conteúdo relacionado

Mais procurados

Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentationadamcookeuk
 
Ruby and Rails by example
Ruby and Rails by exampleRuby and Rails by example
Ruby and Rails by examplebryanbibat
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRaimonds Simanovskis
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes BackBurke Libbey
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyNick Sieger
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: PrototypesVernon Kesner
 
TYPO3 Flow 2.0 Workshop T3BOARD13
TYPO3 Flow 2.0 Workshop T3BOARD13TYPO3 Flow 2.0 Workshop T3BOARD13
TYPO3 Flow 2.0 Workshop T3BOARD13Robert Lemke
 
Minicurso Ruby e Rails
Minicurso Ruby e RailsMinicurso Ruby e Rails
Minicurso Ruby e RailsSEA Tecnologia
 
Spring into rails
Spring into railsSpring into rails
Spring into railsHiro Asari
 
Chef on MongoDB and Pyramid
Chef on MongoDB and PyramidChef on MongoDB and Pyramid
Chef on MongoDB and PyramidRick Copeland
 
Cassandra Client Tutorial
Cassandra Client TutorialCassandra Client Tutorial
Cassandra Client TutorialJoe McTee
 
Using Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRBUsing Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRBHiro Asari
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 

Mais procurados (20)

Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Ruby and Rails by example
Ruby and Rails by exampleRuby and Rails by example
Ruby and Rails by example
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes Back
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
 
JRuby and You
JRuby and YouJRuby and You
JRuby and You
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
 
TYPO3 Flow 2.0 Workshop T3BOARD13
TYPO3 Flow 2.0 Workshop T3BOARD13TYPO3 Flow 2.0 Workshop T3BOARD13
TYPO3 Flow 2.0 Workshop T3BOARD13
 
Minicurso Ruby e Rails
Minicurso Ruby e RailsMinicurso Ruby e Rails
Minicurso Ruby e Rails
 
Spring into rails
Spring into railsSpring into rails
Spring into rails
 
Chef on MongoDB and Pyramid
Chef on MongoDB and PyramidChef on MongoDB and Pyramid
Chef on MongoDB and Pyramid
 
Cassandra Client Tutorial
Cassandra Client TutorialCassandra Client Tutorial
Cassandra Client Tutorial
 
Using Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRBUsing Java from Ruby with JRuby IRB
Using Java from Ruby with JRuby IRB
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Coffee Script
Coffee ScriptCoffee Script
Coffee Script
 

Semelhante a Rails for zombies_2_cheatsheets

Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentNicolas Ledez
 
Rails Model Basics
Rails Model BasicsRails Model Basics
Rails Model BasicsJames Gray
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 
Rails2 Pr
Rails2 PrRails2 Pr
Rails2 Prxibbar
 
Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à RubyMicrosoft
 
Database schema management in Ruby apps
Database schema management in Ruby appsDatabase schema management in Ruby apps
Database schema management in Ruby appsVsevolod Romashov
 
Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009Hussein Morsy
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introductionTse-Ching Ho
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developergicappa
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发shaokun
 
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...Matt Gauger
 
Ruby On Rails Introduction
Ruby On Rails IntroductionRuby On Rails Introduction
Ruby On Rails IntroductionThomas Fuchs
 
Moose - YAPC::NA 2012
Moose - YAPC::NA 2012Moose - YAPC::NA 2012
Moose - YAPC::NA 2012xSawyer
 
wwc start-launched
wwc start-launchedwwc start-launched
wwc start-launchedMat Schaffer
 
TDC 2012 - Patterns e Anti-Patterns em Ruby
TDC 2012 - Patterns e Anti-Patterns em RubyTDC 2012 - Patterns e Anti-Patterns em Ruby
TDC 2012 - Patterns e Anti-Patterns em RubyFabio Akita
 

Semelhante a Rails for zombies_2_cheatsheets (20)

From dot net_to_rails
From dot net_to_railsFrom dot net_to_rails
From dot net_to_rails
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirent
 
Rails Model Basics
Rails Model BasicsRails Model Basics
Rails Model Basics
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Rails2 Pr
Rails2 PrRails2 Pr
Rails2 Pr
 
Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à Ruby
 
Database schema management in Ruby apps
Database schema management in Ruby appsDatabase schema management in Ruby apps
Database schema management in Ruby apps
 
Curso rails
Curso railsCurso rails
Curso rails
 
DataMapper
DataMapperDataMapper
DataMapper
 
Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009Datamapper Railskonferenz 2009
Datamapper Railskonferenz 2009
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introduction
 
Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developer
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
 
From dot net_to_rails
From dot net_to_railsFrom dot net_to_rails
From dot net_to_rails
 
Ruby On Rails Introduction
Ruby On Rails IntroductionRuby On Rails Introduction
Ruby On Rails Introduction
 
Moose - YAPC::NA 2012
Moose - YAPC::NA 2012Moose - YAPC::NA 2012
Moose - YAPC::NA 2012
 
wwc start-launched
wwc start-launchedwwc start-launched
wwc start-launched
 
TDC 2012 - Patterns e Anti-Patterns em Ruby
TDC 2012 - Patterns e Anti-Patterns em RubyTDC 2012 - Patterns e Anti-Patterns em Ruby
TDC 2012 - Patterns e Anti-Patterns em Ruby
 

Último

Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 

Último (20)

Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 

Rails for zombies_2_cheatsheets

  • 1. Migrations 1 of 10 To Create a Blank Migration: rails g migration <name> To Add Columns: rails g migration Add<Anything>To<TableName> [columnName:type] To Remove Columns: rails g migration Remove<Anything>From<TableName> [columnName:type] Column Options Migration Methods* Active Record Supported Types default: <value> create_table change_table :primary_key :string limit: 30 drop_table add_column :text :integer null: false change_column rename_column :float :decimal first: true remove_column add_index :datetime :timestamp after: :email remove_index :time :date unique: true :binary :boolean * See documentation for syntax Remove Column Add Column rails g migration RemoveAgeFromZombies age:integer rails g migration AddEmailToZombies email:string class RemoveAgeFromZombies < ActiveRecord::Migration class AddEmailToZombies < ActiveRecord::Migration def up def up remove_column :zombies, :age add_column :zombies, :email, :string end end def down def down add_column :zombies, :age, :integer remove_column :zombies, :email end end end end Create Table Don’t Forget to Rake! rails g migration CreateZombiesTable name:string, bio:text, age:integer $ rake db:migrate Run all missing migrations class CreateZombiesTable < ActiveRecord::Migration $ rake db:rollback def up Rollback the previous migration create_table :zombies do |t| t.string :name $ rake db:setup t.text :bio Create db, load schema & seed t.integer :age $ rake db:schema:dump t.timestamps Dump the current db state end end db/schema.rb def down drop_table :zombies end end Resources: http://guides.rubyonrails.org/migrations.html
  • 2. Rails Command Line 2 of 10 Command Shortcut Description rails new <app name> # creates a new Rails application rails server rails s # starts up the Rails server rails generate rails g # generates template code Help: rails console rails c # starts up the Rails console All commands can be run with -h for more information rails dbconsole rails db # starts up the Rails db console Generate Examples rails g scaffold zombie name:string bio:text age:integer rails g migration RemoveEmailFromUser email:string rails g mailer ZombieMailer decomp_change lost_brain Models Named Scope Examples class Zombie < ActiveRecord::Base Zombie.rotting scope :rotting, where(rotting: true) Zombie.fresh scope :fresh, where(“age < 20”) Zombie.recent scope :recent, order(“created_at desc”).limit(3) Zombie.rotting.recent end Callbacks Examples before_validation after_validation after_create :send_welcome_email before_save after_save before_save :encrypt_password before_create after_create before_destroy :set_deleted_flag before_update after_update after_update {|zombie| logger.info “Zombie #{zombie.id} updated” } before_destroy after_destroy Self Scope Relationship Options Reading attributes does not require “self ” but setting dependent: :destroy attributes does require “self ” foreign_key: :undead_id primary_key: :zid validate: true class Zombie < ActiveRecord::Base before_save :make_rotting def make_rotting Relational Includes Examples* if age > 20 self.rotting = true @zombies = Zombie.includes(:brain).all end @recent = Zombie.recent.includes(:brain) end * To avoid extra queries end
  • 3. REST & Routes 3 of 10 Rake Routes Generates $ rake routes zombies GET /zombies {:action=>”index”, :controller=>”zombies”} POST /zombies {:action=>”create”, :controller=>”zombies”} - Prints your RESTful routes new_zombie GET /zombies/new {:action=>”new”, :controller=>”zombies”} edit_zombie GET /zombies/:id/edit {:action=>”edit”, :controller=>”zombies”} zombie GET /zombies/:id {:action=>”show”, :controller=>”zombies”} PUT /zombies/:id {:action=>”update”, :controller=>”zombies”} DELETE /zombies/:id {:action=>”destroy”, :controller=>”zombies”} Example Link To Usage Relative Paths Path Generated <%= link_to 'All Zombies', zombies_path %> zombies_path /zombies <%= link_to 'New Zombie', new_zombie_path %> new_zombie_path /zombies/new <%= link_to 'Edit Zombie', edit_zombie_path(@zombie) %> <%= link_to 'Show Zombie', zombie_path(@zombie) %> Absolute Paths URL Generated <%= link_to 'Show Zombie', @zombie %> <%= link_to 'Delete Zombie', @zombie, method :delete %> zombies_url http://localhost:3000/zombies new_zombie_url http://localhost:3000/zombies/new Forms Example Alternate Text Input Helpers <%= form_for(@zombie) do |f| %> <%= f.password_field :password %> <%= f.text_field :name %> <%= f.number_field :price %> <%= f.text_area :bio %> <%= f.range_field :quantity %> <%= f.email_field :email %> <%= f.select :decomp, ['fresh', 'rotting', 'stale'] %> <%= f.url_field :website %> <%= f.select :decomp, [['fresh', 1], ['rotting', 2], ['stale', 3]] %> <%= f.telephone_field :mobile %> <%= f.radio_button :decomp, 'fresh', checked: true %> <%= f.radio_button :decomp, 'rotting' %> <%= f.radio_button :decomp, 'stale' %> <%= f.check_box :rotting %> <%= f.submit %> <% end %>
  • 4. Nested Routes 4 of 10 1 app/configure/routes.rb TwitterForZombies::Application.routes.draw do resources :zombies do resources :tweets end end 2 app/controller/tweets_controller.rb class TweetsController < ApplicationController before_filter :get_zombie def get_zombie @zombie = Zombie.find(params[:zombie_id]) end def show /zombies/4/tweets/2 @tweet = @zombie.tweets.find(params[:id]) params = { :zombie_id => 4, :id => 2 } end def create @tweet = @zombie.tweets.new(params[:tweet]) if @tweet.save redirect_to [@zombie, @tweet] else render action: “new” end def index /zombies/4/tweets @tweets = @zombie.tweets params = { :zombie_id => 4 } end end 3 app/views/tweets/_form.html.erb <%= form_for([@zombie, @tweet]) do |f| %> 4 app/views/tweets/index.html.erb <% @tweets.each do |tweet| %> <tr> Look Up URL Helpers $ rake routes <td><%= tweet.body %></td> <td><%= link_to ‘Show’, [@zombie, tweet] %></td> <td><%= link_to ‘Edit’, edit_zombie_tweet_path(@zombie, tweet) %></td> <td><%= link_to ‘Destroy’, [@zombie, tweet], method: :delete %></td> </tr> <% end %> <%= link_to ‘New Tweet’, new_zombie_tweet_path(@zombie) %>
  • 5. View Partials & View Helpers 5 of 10 app/views/tweets/new.html.erb <h1>New tweet</h1> <%= render 'form' %> app/views/tweets/_form.html.erb <%= link_to 'Back', zombie_tweets_path(@zombie) %> <h1>New tweet</h1> <%= render 'form' %> app/views/tweets/edit.html.erb <%= link_to 'Back', zombie_tweets_path(@zombie) %> <h1>Editing tweet</h1> <%= render 'form' %> - Partials start with an underscore View Helper Same As Calls <div id="tweet_<%= tweet.id %>" class="tweet"> <%= div_for tweet do %> dom_id(@tweet) -> #tweet_2 <%= tweet.body %> <%= tweet.body %> </div> <% end %> View Helper Same As Looks For <%= @zombies.each do |zombie| %> <%= render @zombies %> views/zombies/_zombie.html.erb <%= render zombie %> <% end %> Additional Helpers Result <%= truncate("I need brains!", :length => 10) %> I need bra… <%= truncate("I need brains!", :length => 10, :separator => ' ') %> I need… I see <%= pluralize(Zombie.count, "zombie") %> I see 2 zombies / I see 1 zombie His name was <%= @zombie.name.titleize %> His name was Ash Williams Ash’s zombie roles are <%= @role_names.to_sentence %> Ash’s zombie roles are Captain, and Solidier. He was buried alive <%= time_ago_in_words @zombie.created_at %> ago He was buried alive 2 days ago Price is <%= number_to_currency 13.5 %> Price is $13.50 Ash is <%= number_to_human 13234355423 %> years old %> Ash is 13.2 billion years old
  • 6. Creating a Mailer 6 of 10 Generator: rails g mailer ZombieMailer decomp_change lost_brain Mailer Class Example - app/mailers/zombie_mailer.rb Additional Options class ZombieMailer < ActionMailer::Base from: my@email.com default from: "from@example.com" cc: my@email.com bcc: my@email.com def decomp_change(zombie) reply_to: my@email.com @zombie = zombie @last_tweet = @zombie.tweets.last Mass Mailing Notes: Mass mailing is best done outside of attachments['z.pdf'] = File.read("#{Rails.root}/public/zombie.pdf") Rails. You can use gems for services mail to: @zombie.email, subject: 'Your decomp stage has changed' like MadMimi.com if you plan on end sending a lot of mail. end Mailer Text Views - app/views/zombie_mailer/decomp_change.text.erb Resources: http://guides.rubyonrails.org/action_ Greetings <%= @zombie.name %> mailer_basics.html Mailer HTML Views - app/views/zombie_mailer/decomp_change.html.erb <h1>Greetings <%= @zombie.name %></h1> Sending Mail - app/models/zombie.rb ZombieMailer.decomp_change(@zombie).deliver Assets & Asset Paths Asset Tag Helpers <%= javascript_include_tag "custom" %> <%= stylesheet_link_tag "style" %> <%= image_tag "rails.png" %> Asset Paths in Stylesheets - app/assets/stylesheets/zombie.css.erb form.new_zombie input.submit { background-image: url(<%= asset_path('button.png') %>); } Using SASS, CoffeeScript Assets To compile with other CSS/JS helpers, just add the necessary extension. Resources: http://sass-lang.org app/assets/stylesheets/zombie.css.scss.erb http://jashkenas.github.com/coffee-script/ app/assets/javascripts/zombies.js.coffee
  • 7. CoffeeScript & jQuery 7 of 10 JavaScript & jQuery CoffeeScript & jQuery app/assets/javascripts/zombie.js app/assets/javascripts/zombie.js.coffee $(document).ready(function() { $(document).ready -> $('#show-bio').click(function(event) { $('#show-bio').click (event) -> event.preventDefault(); event.preventDefault() $(this).hide(); $(this).hide() $('.field#bio').show(); $('.field#bio').show() } } CoffeeScript AJAX Example $(document).ready -> $('div#custom_phase2 form').submit (event) -> event.preventDefault() url = $(this).attr('action') custom_decomp = $('div#custom_phase2 #zombie_decomp').val() $.ajax type: 'put' url: url data: { zombie: { decomp: custom_decomp } } dataType: 'json' success: (json) -> $('#decomp').text(json.decomp).effect('highlight') $('div#custom_phase2').fadeOut() if json.decomp == "Dead (again)" SASS & CSS CSS SASS app/assets/stylesheets/zombie.css.erb app/assets/stylesheets/zombie.css.scss.erb form.new_zombie { form.new_zombie { border: 1px dashed gray; border: 1px dashed gray; } .field#bio { form.new_zombie .field#bio { display: none; display: none; } } input.submit { form.new_zombie input.submit { background-image: url(<%= asset_path('button.png') %>); background-image: url(<%= asset_path('button.png') %>); } } } To Remove SASS/CoffeeScript Default Asset Generation Gemfile gem 'sass-rails' Remove then rerun 'bundle install' gem 'coffee-script'
  • 8. Sprockets & Application.js/.css 8 of 10 app/assets/javascripts/application.js Contains a manifest of the JavaScript files we use //= require jquery Looks for jquery.js in all asset paths //= require jquery_ujs //= require shared Loads: lib/assets/javascripts/shared.js.coffee //= require_tree . app/assets/stylesheet/application.css Contains a manifest of the stylesheets we use /* *= require reset *= require_self Styles in this file are included after the reset stylesheet *= require_tree . */ form.new_zombie { border: 1px dashed gray; } Rendering / HTTP Status Codes Responds_to Example app/controllers/zombies_controller.rb class ZombiesController < ApplicationController def show @zombie = Zombie.find(params[:id]) respond_to do |format| format.html do if @zombie.decomp == 'Dead (again)' render :dead_again Renders app/views/zombies/dead_again.html.erb end Renders app/views/zombies/show.html.erb end format.json { render json: @zombie } Renders JSON end end end HTTP Status Codes JSON Rendering Examples 200 :ok 401 :unauthorized render json: @zombie.errors, status: :unprocessable_entity 201 :created 102 :processing render json: @zombie, status: :created, location: @zombie 422 :unprocessed_entity 404 :not_found
  • 9. Custom Routes 9 of 10 Types Route URL :member get :decomp, on: :member /zombies/:id/decomp acts on a single resource put :decay, on: :member /zombies/:id/decay :collection acts on a collection of resources get :fresh, on: :collection /zombies/fresh post :search, on: :collection /zombies/search Examples <%= link_to 'Fresh zombies', fresh_zombies_path %> <%= form_tag(search_zombies_path) do |f| %> <%= link_to 'Get decomp', decomp_zombie_path(@zombie) %> <%= form_for @zombie, url: decay_zombie_path(@zombie) %> Custom JSON Responses Examples @zombie.to_json(only: :name) @zombie.to_json(except: [:created_at, :updated_at, :id, :email, :bio]) { “name” : “Eric” } { "age":25, "decomp":"Fresh", "name":"Eric", "rotting":false } @zombie.to_json(only: [:name, :age]) @zombie.to_json(include: :brain, except: [:created_at, :updated_at, :id]) { “name” : “Eric”, "age": 25 } { "age":25, "bio":"I am zombified", "decomp":"Fresh", "email":"zom@bied.com", "name":"Eric", "rotting":false, "brain": { "flavor":"Butter", "status":"Smashed", "zombie_id":3 } }
  • 10. AJAX 10 of 10 1 Make a Remote Link or Form Call <%= link_to 'delete', zombie, method: :delete, remote: true %> <a href="/zombies/5" data-method="delete" data-remote="true" rel="nofollow">delete</a> <%= form_for (@zombie, remote: true) do |f| %> <form action="/zombies" data-remote="true" method="post"> 2 Ensure the Controller Can Accept JavaScript Calls respond_to do |format| format.js end 3 Write the JavaScript to Return to the Client app/views/zombies/<action name>.js.erb $('#<%= dom_id(@zombie) %>').fadeOut(); Other jQuery Actions $('<selector>').append(<content or jQuery object>); $('<selector>').effect('highlight'); Requires jQuery UI $('<selector>').text(<string>);