Ruby On Rails Guides v2 - Ruby On Rails
Ruby On Rails Guides v2 - Ruby On Rails
Front Matter
Ruby on Rails Guides (v5.0.0.1)
Credits
Getting Started with Rails Ruby on...
1 Guide Assumptions
2 What is Rails?
3 Creating a New Rails Project
4 Hello, Rails!
5 Getting Up and Running
6 Adding a Second Model
7 Refactoring
8 Deleting Comments
9 Security
10 What's Next?
11 Configuration Gotchas
Active Record Basics Ruby on Rails...
1 What is Active Record?
2 Convention over Configuration in Active Record
3 Creating Active Record Models
4 Overriding the Naming Conventions
5 CRUD: Reading and Writing Data
6 Validations
7 Callbacks
8 Migrations
10 Transaction Callbacks
Active Record Associations Ruby on...
1 Why Associations?
2 The Types of Associations
3 Tips, Tricks, and Warnings
4 Detailed Association Reference
5 Single Table Inheritance
Active Record Query Interface Ruby...
1 Retrieving Objects from the Database
2 Conditions
3 Ordering
4 Selecting Specific Fields
5 Limit and Offset
6 Group
7 Having
8 Overriding Conditions
9 Null Relation
10 Readonly Objects
11 Locking Records for Update
12 Joining Tables
13 Eager Loading Associations
14 Scopes
15 Dynamic Finders
16 Enums
17 Understanding The Method Chaining
18 Find or Build a New Object
19 Finding by SQL
20 Existence of Objects
21 Calculations
22 Running EXPLAIN
Active Model Basics Ruby on Rails...
1 Introduction
Action View Overview Ruby on Rails...
1 What is Action View?
2 Using Action View with Rails
3 Templates, Partials and Layouts
4 Partial Layouts
5 View Paths
6 Overview of helpers provided by Action View
7 Localized Views
Layouts and Rendering in Rails Ruby...
1 Overview: How the Pieces Fit Together
2 Creating Responses
3 Structuring Layouts
Form Helpers Ruby on Rails Guides
1 Dealing with Basic Forms
2 Dealing with Model Objects
3 Making Select Boxes with Ease
4 Using Date and Time Form Helpers
5 Uploading Files
6 Customizing Form Builders
7 Understanding Parameter Naming Conventions
8 Forms to External Resources
4 Extensions to Class
5 Extensions to String
6 Extensions to Numeric
7 Extensions to Integer
8 Extensions to BigDecimal
9 Extensions to Enumerable
10 Extensions to Array
11 Extensions to Hash
12 Extensions to Regexp
13 Extensions to Range
14 Extensions to Date
15 Extensions to DateTime
16 Extensions to Time
17 Extensions to File
18 Extensions to Marshal
19 Extensions to NameError
20 Extensions to LoadError
Rails Internationalization (I18n) API...
1 How I18n in Ruby on Rails Works
2 Setup the Rails Application for Internationalization
3 Internationalization and Localization
4 Overview of the I18n API Features
5 How to Store your Custom Translations
6 Customize your I18n Setup
7 Conclusion
8 Contributing to Rails I18n
9 Resources
10 Authors
11 Footnotes
Action Mailer Basics Ruby on Rails...
1 Introduction
2 Sending Emails
3 Receiving Emails
4 Action Mailer Callbacks
5 Using Action Mailer Helpers
6 Action Mailer Configuration
7 Mailer Testing
8 Intercepting Emails
Active Job Basics Ruby on Rails Guides
1 Introduction
2 The Purpose of Active Job
3 Creating a Job
4 Job Execution
5 Queues
6 Callbacks
7 Action Mailer
8 Internationalization
9 GlobalID
10 Exceptions
11 Job Testing
A Guide to Testing Rails Applications...
1 Why Write Tests for your Rails Applications?
2 Introduction to Testing
3 The Test Database
4 Model Testing
5 Integration Testing
6 Functional Tests for Your Controllers
7 Testing Routes
8 Testing Views
9 Testing Helpers
10 Testing Your Mailers
11 Testing Jobs
12 Additional Testing Resources
Ruby on Rails Security Guide Ruby on...
1 Introduction
2 Sessions
3 Cross-Site Request Forgery (CSRF)
4 Redirection and Files
5 Intranet and Admin Security
6 User Management
7 Injection
8 Unsafe Query Generation
9 Default Headers
10 Environmental Security
11 Additional Resources
Debugging Rails Applications Ruby on...
1 View Helpers for Debugging
2 The Logger
3 Debugging with the byebug gem
4 Debugging with the web-console gem
5 Debugging Memory Leaks
6 Plugins for Debugging
7 References
Configuring Rails Applications Ruby...
1 Locations for Initialization Code
2 Running Code Before Rails
5 Turbolinks
6 Other Resources
The Rails Initialization Process ...
1 Launch!
2 Loading Rails
Autoloading and Reloading Constants ...
1 Introduction
2 Constants Refresher
3 Vocabulary
4 Autoloading Availability
5 autoload_paths
6 Autoloading Algorithms
7 require_dependency
8 Constant Reloading
9 Module#autoload isn't Involved
10 Common Gotchas
Caching with Rails: An Overview Ruby...
1 Basic Caching
2 Cache Stores
3 Cache Keys
4 Conditional GET support
5 References
Active Support Instrumentation Ruby...
1 Introduction to instrumentation
10 Deployment
The Basics of Creating Rails Plugins ...
1 Setup
2 Testing Your Newly Generated Plugin
3 Extending Core Classes
4 Add an "acts_as" Method to Active Record
5 Generators
6 Publishing Your Gem
7 RDoc Documentation
Rails on Rack Ruby on Rails Guides
1 Introduction to Rack
2 Rails on Rack
3 Action Dispatcher Middleware Stack
4 Resources
Creating and Customizing Rails...
1 First Contact
2 Creating Your First Generator
3 Creating Generators with Generators
4 Generators Lookup
5 Customizing Your Workflow
6 Customizing Your Workflow by Changing Generators Templates
7 Adding Generators Fallbacks
8 Application Templates
9 Generator methods
Getting Started with Engines Ruby on...
1 Markdown
2 Prologue
3 Headings
4 API Documentation Guidelines
5 HTML Guides
6 Kindle Guides
Maintenance Policy for Ruby on Rails ...
1 New Features
2 Bug Fixes
3 Security Issues
4 Severe Security Issues
5 Unsupported Release Series
A Guide for Upgrading Ruby on Rails ...
1 General Advice
2 Upgrading from Rails 4.2 to Rails 5.0
3 Upgrading from Rails 4.1 to Rails 4.2
4 Upgrading from Rails 4.0 to Rails 4.1
5 Upgrading from Rails 3.2 to Rails 4.0
6 Upgrading from Rails 3.1 to Rails 3.2
7 Upgrading from Rails 3.0 to Rails 3.1
Ruby on Rails 5.0 Release Notes Ruby...
1 Upgrading to Rails 5.0
2 Major Features
3 Railties
4 Action Pack
5 Action View
6 Action Mailer
7 Active Record
8 Active Model
9 Active Job
10 Active Support
11 Credits
Ruby on Rails 4.2 Release Notes Ruby...
1 Upgrading to Rails 4.2
2 Major Features
3 Incompatibilities
4 Railties
5 Action Pack
6 Action View
7 Action Mailer
8 Active Record
9 Active Model
10 Active Support
11 Credits
Ruby on Rails 4.1 Release Notes Ruby...
1 Upgrading to Rails 4.1
2 Major Features
3 Railties
4 Action Pack
5 Action Mailer
6 Active Record
7 Active Model
8 Active Support
9 Credits
Ruby on Rails 4.0 Release Notes Ruby...
4 Railties
5 Action Pack
6 Active Record
7 Active Model
8 Active Resource
9 Active Support
10 Credits
Ruby on Rails 3.0 Release Notes Ruby...
1 Upgrading to Rails 3
2 Creating a Rails 3.0 application
3 Rails Architectural Changes
4 Documentation
5 Internationalization
6 Railties
7 Action Pack
8 Active Model
9 Active Record
10 Active Resource
11 Active Support
12 Action Mailer
13 Credits
Ruby on Rails 2.3 Release Notes Ruby...
1 Application Architecture
2 Documentation
3 Ruby 1.9.1 Support
4 Active Record
5 Action Controller
6 Action View
7 Active Support
8 Railties
9 Deprecated
10 Credits
Ruby on Rails 2.2 Release Notes Ruby...
1 Infrastructure
2 Documentation
3 Better integration with HTTP : Out of the box ETag support
4 Thread Safety
5 Active Record
6 Action Controller
7 Action View
8 Action Mailer
9 Active Support
10 Railties
11 Deprecated
12 Credits
Front Matter
Credits
We'd like to thank the following people for their tireless contributions to
this project.
Vijay Dev
Vijayakumar, found as Vijay Dev on the web, is a web applications
developer and an open source enthusiast who lives in Chennai, India. He
started using Rails in 2009 and began actively contributing to Rails
documentation in late 2010. He tweets a lot and also blogs.
Xavier Noria
Xavier Noria has been into Ruby on Rails since 2005. He is a Rails core
team member and enjoys combining his passion for Rails and his past life
as a proofreader of math textbooks. Xavier is currently an independent
Ruby on Rails consultant. Oh, he also tweets and can be found everywhere
as "fxn".
Rails Guides Designers
Jason Zimdars
Jason Zimdars is an experienced creative director and web designer who
has lead UI and UX design for numerous websites and web applications.
You can see more of his design and writing at Thinkcage.com or follow
him on Twitter.
Rails Guides Authors
Ryan Bigg
Ryan Bigg works as a Rails developer at Marketplacer and has been
working with Rails since 2006. He's the author of Multi Tenancy With
Rails and co-author of Rails 4 in Action. He's written many gems which
can be seen on his GitHub page and he also tweets prolifically as
@ryanbigg.
Frederick Cheung
Frederick Cheung is Chief Wizard at Texperts where he has been using
Rails since 2006. He is based in Cambridge (UK) and when not consuming
fine ales he blogs at spacevatican.org.
Tore Darell
Tore Darell is an independent developer based in Menton, France who
specialises in cruft-free web applications using Ruby, Rails and
unobtrusive JavaScript. You can follow him on Twitter.
Jeff Dean
Jeff Dean is a software engineer with Pivotal Labs.
Mike Gunderloy
Mike Gunderloy is a consultant with ActionRails. He brings 25 years of
experience in a variety of languages to bear on his current work with Rails.
His near-daily links and other blogging can be found at A Fresh Cup and
he twitters too much.
Mikel Lindsaar
Mikel Lindsaar has been working with Rails since 2006 and is the author
of the Ruby Mail gem and core contributor (he helped re-write Action
Mailer's API). Mikel is the founder of RubyX, has a blog and tweets.
Cssio Marques
Cssio Marques is a Brazilian software developer working with different
programming languages such as Ruby, JavaScript, CPP and Java, as an
independent consultant. He blogs at /* CODIFICANDO */, which is
mainly written in Portuguese, but will soon get a new section for posts
James Miller
James Miller is a software developer for JK Tech in San Diego, CA. You
can find James on GitHub, Gmail, Twitter, and Freenode as "bensie".
Pratik Naik
Pratik Naik is a Ruby on Rails developer at Basecamp and also a member
of the Rails core team. He maintains a blog at has_many :bugs, :through
=> :rails and has a semi-active twitter account.
Emilio Tagua
Emilio Tagua a.k.a. miloops is an Argentinian entrepreneur,
developer, open source contributor and Rails evangelist. Cofounder of
Eventioz. He has been using Rails since 2006 and contributing since early
2008. Can be found at gmail, twitter, freenode, everywhere as "miloops".
Heiko Webers
Heiko Webers is the founder of bauland42, a German web application
security consulting and development company focused on Ruby on Rails.
He blogs at the Ruby on Rails Security Project. After 10 years of desktop
application development, Heiko has rarely looked back.
Akshay Surve
Akshay Surve is the Founder at DeltaX, hackathon specialist, a midnight
code junkie and occasionally writes prose. You can connect with him on
Twitter, Linkedin, Personal Blog or Quora.
This work is licensed under a Creative Commons Attribution-ShareAlike
4.0 International License
"Rails", "Ruby on Rails", and the Rails logo are trademarks of David
Heinemeier Hansson. All rights reserved.
1 Guide Assumptions
This guide is designed for beginners who want to get started with a Rails
application from scratch. It does not assume that you have any prior
experience with Rails. However, to get the most out of it, you need to have
some prerequisites installed:
The Ruby language version 2.2.2 or newer.
Right version of Development Kit, if you are using Windows.
The RubyGems packaging system, which is installed with Ruby by
default. To learn more about RubyGems, please read the RubyGems
Guides.
A working installation of the SQLite3 Database.
Rails is a web application framework running on the Ruby programming
language. If you have no prior experience with Ruby, you will find a very
steep learning curve diving straight into Rails. There are several curated
lists of online resources for learning Ruby:
Official Ruby Programming Language website
List of Free Programming Books
Be aware that some resources, while still excellent, cover versions of Ruby
as old as 1.6, and commonly 1.8, and will not include some syntax that you
will see in day-to-day development with Rails.
2 What is Rails?
Rails is a web application development framework written in the Ruby
language. It is designed to make programming web applications easier by
making assumptions about what every developer needs to get started. It
allows you to write less code while accomplishing more than many other
languages and frameworks. Experienced Rails developers also report that
it makes web application development more fun.
Rails is opinionated software. It makes the assumption that there is a
"best" way to do things, and it's designed to encourage that way - and in
some cases to discourage alternatives. If you learn "The Rails Way" you'll
probably discover a tremendous increase in productivity. If you persist in
bringing old habits from other languages to your Rails development, and
trying to use patterns you learned elsewhere, you may have a less happy
experience.
The Rails philosophy includes two major guiding principles:
Don't Repeat Yourself: DRY is a principle of software development
which states that "Every piece of knowledge must have a single,
unambiguous, authoritative representation within a system." By not
writing the same information over and over again, our code is more
maintainable, more extensible, and less buggy.
Convention Over Configuration: Rails has opinions about the best
way to do many things in a web application, and defaults to this set of
conventions, rather than require that you specify every minutiae
through endless configuration files.
A number of tools exist to help you quickly install Ruby and Ruby on
Rails on your system. Windows users can use Rails Installer, while Mac
OS X users can use Tokaido. For more installation methods for most
Operating Systems take a look at ruby-lang.org.
Many popular UNIX-like OSes ship with an acceptable version of
SQLite3. On Windows, if you installed Rails through Rails Installer, you
already have SQLite installed. Others can find installation instructions at
the SQLite3 website. Verify that it is correctly installed and in your
PATH:
$ sqlite3 --version
To verify that you have everything installed correctly, you should be able
to run the following:
$ rails --version
This will create a Rails application called Blog in a blog directory and
install the gem dependencies that are already mentioned in Gemfile using
bundle install.
You can see all of the command line options that the Rails application
builder accepts by running rails new -h.
After you create the blog application, switch to its folder:
$ cd blog
The blog directory has a number of auto-generated files and folders that
make up the structure of a Rails application. Most of the work in this
tutorial will happen in the app folder, but here's a basic rundown on the
function of each of the files and folders that Rails created by default:
File/Folder
Purpose
Contains the controllers, models, views, helpers, mailers
app/
and assets for your application. You'll focus on this folder
for the remainder of this guide.
Contains the rails script that starts your app and can
bin/
contain other scripts you use to setup, update, deploy or
run your application.
Configure your application's routes, database, and more.
config/
This is covered in more detail in Configuring Rails
Applications.
Rack configuration for Rack based servers used to start the
config.ru
application.
Contains your current database schema, as well as the
db/
database migrations.
These files allow you to specify what gem dependencies
Gemfile
are needed for your Rails application. These files are used
Gemfile.lock by the Bundler gem. For more information about Bundler,
see the Bundler website.
lib/
Extended modules for your application.
log/
Application log files.
4 Hello, Rails!
To begin with, let's get some text up on screen quickly. To do this, you
need to get your Rails application server running.
4.1 Starting up the Web Server
You actually have a functional Rails application already. To see it, you
need to start a web server on your development machine. You can do this
by running the following in the blog directory:
$ bin/rails server
If you are using Windows, you have to pass the scripts under the bin
folder directly to the Ruby interpreter e.g. ruby bin\rails server.
Compiling CoffeeScript and JavaScript asset compression requires you
have a JavaScript runtime available on your system, in the absence of a
runtime you will see an execjs error during asset compilation. Usually
Mac OS X and Windows come with a JavaScript runtime installed. Rails
adds the therubyracer gem to the generated Gemfile in a commented line
for new apps and you can uncomment if you need it. therubyrhino is the
recommended runtime for JRuby users and is added by default to the
Gemfile in apps generated under JRuby. You can investigate all the
supported runtimes at ExecJS.
This will fire up Puma, a web server distributed with Rails by default. To
see your application in action, open a browser window and navigate to
http://localhost:3000. You should see the Rails default information page:
To stop the web server, hit Ctrl+C in the terminal window where it's
running. To verify the server has stopped you should see your command
prompt cursor again. For most UNIX-like systems including Mac OS X
this will be a dollar sign $. In development mode, Rails does not generally
require you to restart the server; changes you make in files will be
automatically picked up by the server.
The "Welcome aboard" page is the smoke test for a new Rails application:
it makes sure that you have your software configured correctly enough to
serve a page.
4.2 Say "Hello", Rails
To get Rails saying "Hello", you need to create at minimum a controller
and a view.
A controller's purpose is to receive specific requests for the application.
Routing decides which controller receives which requests. Often, there is
more than one route to each controller, and different routes can be served
by different actions. Each action's purpose is to collect information to
provide it to a view.
A view's purpose is to display this information in a human readable
format. An important distinction to make is that it is the controller, not the
view, where information is collected. The view should just display that
information. By default, view templates are written in a language called
eRuby (Embedded Ruby) which is processed by the request cycle in Rails
before being sent to the user.
To create a new controller, you will need to run the "controller" generator
and tell it you want a controller called "Welcome" with an action called
"index", just like this:
$ bin/rails generate controller Welcome index
create test/controllers/welcome_controller_test.rb
invoke helper
create app/helpers/welcome_helper.rb
invoke assets
invoke coffee
create app/assets/javascripts/welcome.coffee
invoke scss
create app/assets/stylesheets/welcome.scss
# For details on the DSL available within this file, see http:
end
This is your application's routing file which holds entries in a special DSL
(domain-specific language) that tells Rails how to connect incoming
requests to controllers and actions. Edit this file by adding the line of code
root 'welcome#index'. It should look something like the following:
Rails.application.routes.draw do
get 'welcome/index'
root 'welcome#index'
end