SlideShare a Scribd company logo
1 of 12
Download to read offline
Ruby on Rails Tutorial
  Learn Rails by Example


      Michael Hartl
2
Contents

1   Introduction                                                                                                                                                                       5
    1.1 Technology . . . . . .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   5
    1.2 Sample code and such .     .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   6
         1.2.1 Code samples .      .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   6
         1.2.2 And such . . .      .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   7
    1.3 Figures and tables . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   7
    1.4 Math . . . . . . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   9

2   Lorem ipsum                                                                                                                                                                        11
    2.1 Lorem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .                                                                              11
    2.2 Ipsum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .                                                                              12




                                                                           3
4   CONTENTS
Chapter 1

Introduction

This is a sample document for what will become the Ruby on Rails Tutorial book. It is by no means a real
book yet—there’s even some lorem ipsum text in what follows (see, e.g., Box 1.1 and Chapter 2). Its purpose
is to show that all the elements are in place to produce a pleasing final product, and to give a hint of what that
final product might eventually look like.


Box 1.1. Cicero dixit

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat.
    Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Ex-
cepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.




1.1        Technology
Rails Tutorial is written in PolyTEXnic, a dialect of the LTEX technical typesetting system (which in turn
                                                          A

is based on TEX). I wrote PolyTEXnic because I wanted to produce both beautiful PDF (and hence print)
documents and pretty HTML documents at the same time, from the same source file. As a result, this
sample document is available both as HTML and as a PDF download. Both formats come with plenty of rich
book-y goodness, including a linked table of contents; numbered sections, tables, figures, and code listings;
linked cross references; syntax highlighting; numbered, shaded sidebars (Box 1.1); footnotes1 ; and even math
(Section 1.4).
    Currently, PolyTEXnic is only available for my private use, but I plan to release it as an open-source
project once it’s battle-tested and ready for general consumption.

  1 Like   this.


                                                       5
6                                                                         CHAPTER 1. INTRODUCTION

1.2     Sample code and such
Often, Rails books include lots of code samples and such. Let’s look at some examples of how PolyTEXnic
makes them both useful and pretty.

1.2.1    Code samples
We’ll likely have some Ruby code in our Rails tutorial, with snippets such as the following:
Listing 1.1. Part of the ClassMethods module in ActiveRecord::Validations.


module ClassMethods
  .
  .
  .
  # File rails-2.3.2/activerecord/lib/active_record/validations.rb, line 511
  def validates_presence_of(*attr_names)
    configuration = { :on => :save }
    configuration.update(attr_names.extract_options!)

    # can’t use validates_each here, because it cannot cope with
    # nonexistent attributes, while errors.add_on_empty can
    send(validation_method(configuration[:on]), configuration) do |record|
      record.errors.add_on_blank(attr_names, configuration[:message])
    end
  end
  .
  .
  .
end


    Note that Listing 1.1 is both syntax-highlighted and numbered—and, as you can see, it can be cross-
referenced as well.
    Of course, we’re not limited to vanilla Ruby; let’s also include some embedded Ruby:
Listing 1.2. The index.html.erb file for the People controller.


<%- column_div :type => :primary do -%>
  <% unless @people.empty? -%>
    <h2>People</h2>
    <%= will_paginate %>
    <ul class="list people">
      <%= render :partial => @people %>
    </ul>
    <%= will_paginate %>
  <% end -%>
<%- end -%>

<%- column_div :type => :secondary do -%>
1.3. FIGURES AND TABLES                                                                                      7


  <%= render :partial => ’searches/box’ %>
  <%= render :partial => ’shared/minifeed’ %>
<%- end -%>


   In fact, we can include code in virtually any language and get nice syntax highlighting for free via the
excellent Pygments program:


;; Common Lisp
;; Return the square of the given number.
(defun square (x)
  "Calculates the square of the single-float x."
  (declare (single-float x) (optimize (speed 3) (debug 0) (safety 1)))
  (* x x))


    Note here that we have a nice highlighted code block, but no listing number. This is useful for short
snippets that aren’t likely ever to be referenced.


1.2.2      And such
Code isn’t everything; sometimes you just want to show shell commands. No problem:


$ rake -T db
(in /Users/mhartl/rails/rails_tutorial)
rake backup:db                       # Backup the current database.
rake db:avatars:delete               # Delete all the avatars.
rake db:avatars:load                 # Make sample avatars.
.
.
.


     We can also include console sessions:


>>   a = 1
=>   1
>>   puts a
1
=>   nil




1.3      Figures and tables
It’s easy to include figures, such as screenshots (Fig. 1.1). (These are particularly useful for a tutorial.) We
can also make tables. I don’t have nice styling yet, but you get the idea (Table 1.1).
8                                                 CHAPTER 1. INTRODUCTION




    Figure 1.1: A screenshot of the Rails Tutorial site.




                  Foo bar     Baz Quux
                 foo bar      baz quux


                 Table 1.1: An ugly table.
1.4. MATH                                                                                                                               9

1.4        Math
While LTEX is great for writing a programming book, DocBook might have worked as well, and rumor has
       A

it DocBook can be converted to HTML. So why bother writing my own system? I went with LTEX for two
                                                                                        A

main reasons:

   1. I don’t know DocBook, but I know LTEX well, so I could be confident in being able to hack something
                                       A

      together.
   2. LTEX is great at math typesetting.
      A


    Though I expect Rails Tutorial will have little or no math, eventually I’d like to use this system to write
math-heavy articles and books, and DocBook can’t do math typesetting. So, in reality, the second consid-
eration alone was decisive, and—if you care about math typesetting—it’s not hard to see why; consider,
for example, the exponential decay factor e−t/τ , or the time-independent Schr¨ dinger equation in quantum
                                                                                 o
mechanics:

                                                          ¯2
                                                          h     2
                                                      −             +V     ψ = Eψ
                                                          2m
Both these math examples look great by construction in the PDF version of this document (since LTEX is a
                                                                                                     A

master math typesetter), but if you’re viewing them on the web you’ll see that they look great there, too.
    How does this work? I began with the only place I’d seen nice math typesetting on the web: Wikipedia’s
math articles.2 This had always been a mystery, because all the nice math typesetting I’d ever seen was
produced by LTEX(or by TEX itself). So how does Wikipedia do it? Well, Wikipedia is built on top of
               A

MediaWiki, and MediaWiki comes bundled with a program called texvc that converts wiki math markup to
pretty PNGs using—wait for it—LTEX. So PolyTEXnic, like MediaWiki, just uses texvc under the hood.3
                                   A




   2 Not  quite true: MathWorld looks nice, too, but it’s closed-source.
   3 Ifyou look at the MediaWiki source to find out how it does math conversion, you’ll see that it’s literally just a shell call to texvc,
so that’s what I did as well.
10   CHAPTER 1. INTRODUCTION
Chapter 2

Lorem ipsum

We certainly expect to have more than one chapter in this book. Here’s the start of a second one.


2.1     Lorem
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim
id est laborum.

Listing 2.1. The Forum model.


# == Schema Information
# Schema version: 20080916002106
#
# Table name: forums
#
# id            :integer(4)      not null, primary key
# name          :string(255)
# description :text
# topics_count :integer(4)       default(0), not null
# created_at    :datetime
# updated_at    :datetime
#

class Forum < ActiveRecord::Base
  attr_accessible :name, :description

  has_many :topics, :order => "created_at DESC", :dependent => :destroy
  has_many :posts, :through => :topics


  validates_length_of :name, :maximum => 255, :allow_nil => true


                                                     11
12                                                                          CHAPTER 2. LOREM IPSUM


  validates_length_of :description, :maximum => 1000, :allow_nil => true
end




2.2     Ipsum
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim
id est laborum.

More Related Content

Similar to rails_tutorial

Getting started erlang
Getting started erlangGetting started erlang
Getting started erlangKwanzoo Dev
 
Wise Document Translator Report
Wise Document Translator ReportWise Document Translator Report
Wise Document Translator ReportRaouf KESKES
 
Sample thesis
Sample thesisSample thesis
Sample thesiskmmanuel
 
Document Object Model (DOM) Level 1 Specification
Document Object Model (DOM) Level 1 SpecificationDocument Object Model (DOM) Level 1 Specification
Document Object Model (DOM) Level 1 SpecificationOtakism
 
robert-kovacsics-part-ii-dissertation
robert-kovacsics-part-ii-dissertationrobert-kovacsics-part-ii-dissertation
robert-kovacsics-part-ii-dissertationRobert Kovacsics
 
A Little Bit Of Help With Maple
A Little Bit Of Help With MapleA Little Bit Of Help With Maple
A Little Bit Of Help With MapleNathan Mathis
 
Machine Vision Toolbox for MATLAB (Relese 3)
Machine Vision Toolbox for MATLAB (Relese 3)Machine Vision Toolbox for MATLAB (Relese 3)
Machine Vision Toolbox for MATLAB (Relese 3)CHIH-PEI WEN
 
The Function Pointer Tutorials
The Function Pointer TutorialsThe Function Pointer Tutorials
The Function Pointer TutorialsNont Banditwong
 
Climb - Property-based dispatch in functional languages [Report]
Climb - Property-based dispatch in functional languages [Report]Climb - Property-based dispatch in functional languages [Report]
Climb - Property-based dispatch in functional languages [Report]Christopher Chedeau
 
A gentle introduction to Latex
A gentle introduction to LatexA gentle introduction to Latex
A gentle introduction to LatexEmmanuel Abatih
 
Key-Value Stores: a practical overview
Key-Value Stores: a practical overviewKey-Value Stores: a practical overview
Key-Value Stores: a practical overviewMarc Seeger
 

Similar to rails_tutorial (20)

Getting started erlang
Getting started erlangGetting started erlang
Getting started erlang
 
Wise Document Translator Report
Wise Document Translator ReportWise Document Translator Report
Wise Document Translator Report
 
Sample thesis
Sample thesisSample thesis
Sample thesis
 
Document Object Model (DOM) Level 1 Specification
Document Object Model (DOM) Level 1 SpecificationDocument Object Model (DOM) Level 1 Specification
Document Object Model (DOM) Level 1 Specification
 
rails.html
rails.htmlrails.html
rails.html
 
rails.html
rails.htmlrails.html
rails.html
 
Te xworks manual
Te xworks manualTe xworks manual
Te xworks manual
 
MapReduce in Cloud Computing
MapReduce in Cloud ComputingMapReduce in Cloud Computing
MapReduce in Cloud Computing
 
robert-kovacsics-part-ii-dissertation
robert-kovacsics-part-ii-dissertationrobert-kovacsics-part-ii-dissertation
robert-kovacsics-part-ii-dissertation
 
A Little Bit Of Help With Maple
A Little Bit Of Help With MapleA Little Bit Of Help With Maple
A Little Bit Of Help With Maple
 
Machine Vision Toolbox for MATLAB (Relese 3)
Machine Vision Toolbox for MATLAB (Relese 3)Machine Vision Toolbox for MATLAB (Relese 3)
Machine Vision Toolbox for MATLAB (Relese 3)
 
The Function Pointer Tutorials
The Function Pointer TutorialsThe Function Pointer Tutorials
The Function Pointer Tutorials
 
Thesis
ThesisThesis
Thesis
 
Climb - Property-based dispatch in functional languages [Report]
Climb - Property-based dispatch in functional languages [Report]Climb - Property-based dispatch in functional languages [Report]
Climb - Property-based dispatch in functional languages [Report]
 
A gentle introduction to Latex
A gentle introduction to LatexA gentle introduction to Latex
A gentle introduction to Latex
 
Cimlvojt 2013bach (1)
Cimlvojt 2013bach (1)Cimlvojt 2013bach (1)
Cimlvojt 2013bach (1)
 
Key-Value Stores: a practical overview
Key-Value Stores: a practical overviewKey-Value Stores: a practical overview
Key-Value Stores: a practical overview
 
Perl-crash-course
Perl-crash-coursePerl-crash-course
Perl-crash-course
 
Perl-crash-course
Perl-crash-coursePerl-crash-course
Perl-crash-course
 
Perl-crash-course
Perl-crash-coursePerl-crash-course
Perl-crash-course
 

More from tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 

More from tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Recently uploaded

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 RobisonAnna Loughnan Colquhoun
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
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 2024The Digital Insurer
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
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 DiscoveryTrustArc
 
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...Drew Madelung
 
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 StrategiesBoston Institute of Analytics
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
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 DevelopmentsTrustArc
 

Recently uploaded (20)

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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
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...
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 

rails_tutorial

  • 1. Ruby on Rails Tutorial Learn Rails by Example Michael Hartl
  • 2. 2
  • 3. Contents 1 Introduction 5 1.1 Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.2 Sample code and such . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.2.1 Code samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.2.2 And such . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.3 Figures and tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.4 Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2 Lorem ipsum 11 2.1 Lorem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 Ipsum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3
  • 4. 4 CONTENTS
  • 5. Chapter 1 Introduction This is a sample document for what will become the Ruby on Rails Tutorial book. It is by no means a real book yet—there’s even some lorem ipsum text in what follows (see, e.g., Box 1.1 and Chapter 2). Its purpose is to show that all the elements are in place to produce a pleasing final product, and to give a hint of what that final product might eventually look like. Box 1.1. Cicero dixit Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Ex- cepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 1.1 Technology Rails Tutorial is written in PolyTEXnic, a dialect of the LTEX technical typesetting system (which in turn A is based on TEX). I wrote PolyTEXnic because I wanted to produce both beautiful PDF (and hence print) documents and pretty HTML documents at the same time, from the same source file. As a result, this sample document is available both as HTML and as a PDF download. Both formats come with plenty of rich book-y goodness, including a linked table of contents; numbered sections, tables, figures, and code listings; linked cross references; syntax highlighting; numbered, shaded sidebars (Box 1.1); footnotes1 ; and even math (Section 1.4). Currently, PolyTEXnic is only available for my private use, but I plan to release it as an open-source project once it’s battle-tested and ready for general consumption. 1 Like this. 5
  • 6. 6 CHAPTER 1. INTRODUCTION 1.2 Sample code and such Often, Rails books include lots of code samples and such. Let’s look at some examples of how PolyTEXnic makes them both useful and pretty. 1.2.1 Code samples We’ll likely have some Ruby code in our Rails tutorial, with snippets such as the following: Listing 1.1. Part of the ClassMethods module in ActiveRecord::Validations. module ClassMethods . . . # File rails-2.3.2/activerecord/lib/active_record/validations.rb, line 511 def validates_presence_of(*attr_names) configuration = { :on => :save } configuration.update(attr_names.extract_options!) # can’t use validates_each here, because it cannot cope with # nonexistent attributes, while errors.add_on_empty can send(validation_method(configuration[:on]), configuration) do |record| record.errors.add_on_blank(attr_names, configuration[:message]) end end . . . end Note that Listing 1.1 is both syntax-highlighted and numbered—and, as you can see, it can be cross- referenced as well. Of course, we’re not limited to vanilla Ruby; let’s also include some embedded Ruby: Listing 1.2. The index.html.erb file for the People controller. <%- column_div :type => :primary do -%> <% unless @people.empty? -%> <h2>People</h2> <%= will_paginate %> <ul class="list people"> <%= render :partial => @people %> </ul> <%= will_paginate %> <% end -%> <%- end -%> <%- column_div :type => :secondary do -%>
  • 7. 1.3. FIGURES AND TABLES 7 <%= render :partial => ’searches/box’ %> <%= render :partial => ’shared/minifeed’ %> <%- end -%> In fact, we can include code in virtually any language and get nice syntax highlighting for free via the excellent Pygments program: ;; Common Lisp ;; Return the square of the given number. (defun square (x) "Calculates the square of the single-float x." (declare (single-float x) (optimize (speed 3) (debug 0) (safety 1))) (* x x)) Note here that we have a nice highlighted code block, but no listing number. This is useful for short snippets that aren’t likely ever to be referenced. 1.2.2 And such Code isn’t everything; sometimes you just want to show shell commands. No problem: $ rake -T db (in /Users/mhartl/rails/rails_tutorial) rake backup:db # Backup the current database. rake db:avatars:delete # Delete all the avatars. rake db:avatars:load # Make sample avatars. . . . We can also include console sessions: >> a = 1 => 1 >> puts a 1 => nil 1.3 Figures and tables It’s easy to include figures, such as screenshots (Fig. 1.1). (These are particularly useful for a tutorial.) We can also make tables. I don’t have nice styling yet, but you get the idea (Table 1.1).
  • 8. 8 CHAPTER 1. INTRODUCTION Figure 1.1: A screenshot of the Rails Tutorial site. Foo bar Baz Quux foo bar baz quux Table 1.1: An ugly table.
  • 9. 1.4. MATH 9 1.4 Math While LTEX is great for writing a programming book, DocBook might have worked as well, and rumor has A it DocBook can be converted to HTML. So why bother writing my own system? I went with LTEX for two A main reasons: 1. I don’t know DocBook, but I know LTEX well, so I could be confident in being able to hack something A together. 2. LTEX is great at math typesetting. A Though I expect Rails Tutorial will have little or no math, eventually I’d like to use this system to write math-heavy articles and books, and DocBook can’t do math typesetting. So, in reality, the second consid- eration alone was decisive, and—if you care about math typesetting—it’s not hard to see why; consider, for example, the exponential decay factor e−t/τ , or the time-independent Schr¨ dinger equation in quantum o mechanics: ¯2 h 2 − +V ψ = Eψ 2m Both these math examples look great by construction in the PDF version of this document (since LTEX is a A master math typesetter), but if you’re viewing them on the web you’ll see that they look great there, too. How does this work? I began with the only place I’d seen nice math typesetting on the web: Wikipedia’s math articles.2 This had always been a mystery, because all the nice math typesetting I’d ever seen was produced by LTEX(or by TEX itself). So how does Wikipedia do it? Well, Wikipedia is built on top of A MediaWiki, and MediaWiki comes bundled with a program called texvc that converts wiki math markup to pretty PNGs using—wait for it—LTEX. So PolyTEXnic, like MediaWiki, just uses texvc under the hood.3 A 2 Not quite true: MathWorld looks nice, too, but it’s closed-source. 3 Ifyou look at the MediaWiki source to find out how it does math conversion, you’ll see that it’s literally just a shell call to texvc, so that’s what I did as well.
  • 10. 10 CHAPTER 1. INTRODUCTION
  • 11. Chapter 2 Lorem ipsum We certainly expect to have more than one chapter in this book. Here’s the start of a second one. 2.1 Lorem Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Listing 2.1. The Forum model. # == Schema Information # Schema version: 20080916002106 # # Table name: forums # # id :integer(4) not null, primary key # name :string(255) # description :text # topics_count :integer(4) default(0), not null # created_at :datetime # updated_at :datetime # class Forum < ActiveRecord::Base attr_accessible :name, :description has_many :topics, :order => "created_at DESC", :dependent => :destroy has_many :posts, :through => :topics validates_length_of :name, :maximum => 255, :allow_nil => true 11
  • 12. 12 CHAPTER 2. LOREM IPSUM validates_length_of :description, :maximum => 1000, :allow_nil => true end 2.2 Ipsum Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.