railties 3.1.1 → 3.1.2.rc1
Sign up to get free protection for your applications and to get access to all the features.
- data/CHANGELOG.md +2382 -0
- data/guides/output/2_2_release_notes.html +565 -0
- data/guides/output/2_3_release_notes.html +713 -0
- data/guides/output/3_0_release_notes.html +652 -0
- data/guides/output/3_1_release_notes.html +670 -0
- data/guides/output/action_controller_overview.html +925 -0
- data/guides/output/action_mailer_basics.html +658 -0
- data/guides/output/action_view_overview.html +1471 -0
- data/guides/output/active_model_basics.html +349 -0
- data/guides/output/active_record_basics.html +364 -0
- data/guides/output/active_record_querying.html +1272 -0
- data/guides/output/active_record_validations_callbacks.html +1292 -0
- data/guides/output/active_resource_basics.html +252 -0
- data/guides/output/active_support_core_extensions.html +3374 -0
- data/guides/output/ajax_on_rails.html +412 -0
- data/guides/output/api_documentation_guidelines.html +317 -0
- data/guides/output/asset_pipeline.html +691 -0
- data/guides/output/association_basics.html +1742 -0
- data/guides/output/caching_with_rails.html +533 -0
- data/guides/output/command_line.html +662 -0
- data/guides/output/configuring.html +811 -0
- data/guides/output/contribute.html +216 -0
- data/guides/output/contributing_to_ruby_on_rails.html +465 -0
- data/guides/output/credits.html +210 -0
- data/guides/output/debugging_rails_applications.html +791 -0
- data/guides/output/engines.html +673 -0
- data/guides/output/form_helpers.html +850 -0
- data/guides/output/generators.html +725 -0
- data/guides/output/getting_started.html +1980 -0
- data/guides/output/i18n.html +1054 -0
- data/guides/output/images/belongs_to.png +0 -0
- data/guides/output/images/book_icon.gif +0 -0
- data/guides/output/images/bullet.gif +0 -0
- data/guides/output/images/challenge.png +0 -0
- data/guides/output/images/chapters_icon.gif +0 -0
- data/guides/output/images/check_bullet.gif +0 -0
- data/guides/output/images/credits_pic_blank.gif +0 -0
- data/guides/output/images/csrf.png +0 -0
- data/guides/output/images/customized_error_messages.png +0 -0
- data/guides/output/images/edge_badge.png +0 -0
- data/guides/output/images/error_messages.png +0 -0
- data/guides/output/images/feature_tile.gif +0 -0
- data/guides/output/images/footer_tile.gif +0 -0
- data/guides/output/images/fxn.png +0 -0
- data/guides/output/images/grey_bullet.gif +0 -0
- data/guides/output/images/habtm.png +0 -0
- data/guides/output/images/has_many.png +0 -0
- data/guides/output/images/has_many_through.png +0 -0
- data/guides/output/images/has_one.png +0 -0
- data/guides/output/images/has_one_through.png +0 -0
- data/guides/output/images/header_backdrop.png +0 -0
- data/guides/output/images/header_tile.gif +0 -0
- data/guides/output/images/i18n/demo_html_safe.png +0 -0
- data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/output/images/i18n/demo_translated_en.png +0 -0
- data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/output/images/i18n/demo_translation_missing.png +0 -0
- data/guides/output/images/i18n/demo_untranslated.png +0 -0
- data/guides/output/images/icons/README +5 -0
- data/guides/output/images/icons/callouts/1.png +0 -0
- data/guides/output/images/icons/callouts/10.png +0 -0
- data/guides/output/images/icons/callouts/11.png +0 -0
- data/guides/output/images/icons/callouts/12.png +0 -0
- data/guides/output/images/icons/callouts/13.png +0 -0
- data/guides/output/images/icons/callouts/14.png +0 -0
- data/guides/output/images/icons/callouts/15.png +0 -0
- data/guides/output/images/icons/callouts/2.png +0 -0
- data/guides/output/images/icons/callouts/3.png +0 -0
- data/guides/output/images/icons/callouts/4.png +0 -0
- data/guides/output/images/icons/callouts/5.png +0 -0
- data/guides/output/images/icons/callouts/6.png +0 -0
- data/guides/output/images/icons/callouts/7.png +0 -0
- data/guides/output/images/icons/callouts/8.png +0 -0
- data/guides/output/images/icons/callouts/9.png +0 -0
- data/guides/output/images/icons/caution.png +0 -0
- data/guides/output/images/icons/example.png +0 -0
- data/guides/output/images/icons/home.png +0 -0
- data/guides/output/images/icons/important.png +0 -0
- data/guides/output/images/icons/next.png +0 -0
- data/guides/output/images/icons/note.png +0 -0
- data/guides/output/images/icons/prev.png +0 -0
- data/guides/output/images/icons/tip.png +0 -0
- data/guides/output/images/icons/up.png +0 -0
- data/guides/output/images/icons/warning.png +0 -0
- data/guides/output/images/jaimeiniesta.jpg +0 -0
- data/guides/output/images/nav_arrow.gif +0 -0
- data/guides/output/images/polymorphic.png +0 -0
- data/guides/output/images/posts_index.png +0 -0
- data/guides/output/images/radar.png +0 -0
- data/guides/output/images/rails_guides_logo.gif +0 -0
- data/guides/output/images/rails_logo_remix.gif +0 -0
- data/guides/output/images/rails_welcome.png +0 -0
- data/guides/output/images/session_fixation.png +0 -0
- data/guides/output/images/tab_grey.gif +0 -0
- data/guides/output/images/tab_info.gif +0 -0
- data/guides/output/images/tab_note.gif +0 -0
- data/guides/output/images/tab_red.gif +0 -0
- data/guides/output/images/tab_yellow.gif +0 -0
- data/guides/output/images/tab_yellow.png +0 -0
- data/guides/output/images/validation_error_messages.png +0 -0
- data/guides/output/images/vijaydev.jpg +0 -0
- data/guides/output/index.html +300 -0
- data/guides/output/initialization.html +1087 -0
- data/guides/output/javascripts/guides.js +7 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
- data/guides/output/javascripts/syntaxhighlighter/shCore.js +17 -0
- data/guides/output/layout.html +312 -0
- data/guides/output/layouts_and_rendering.html +1257 -0
- data/guides/output/migrations.html +751 -0
- data/guides/output/nested_model_forms.html +350 -0
- data/guides/output/performance_testing.html +858 -0
- data/guides/output/plugins.html +590 -0
- data/guides/output/rails_application_templates.html +368 -0
- data/guides/output/rails_on_rack.html +408 -0
- data/guides/output/routing.html +1246 -0
- data/guides/output/ruby_on_rails_guides_guidelines.html +218 -0
- data/guides/output/security.html +968 -0
- data/guides/output/stylesheets/fixes.css +16 -0
- data/guides/output/stylesheets/main.css +445 -0
- data/guides/output/stylesheets/print.css +52 -0
- data/guides/output/stylesheets/reset.css +43 -0
- data/guides/output/stylesheets/style.css +13 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCore.css +226 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
- data/guides/output/testing.html +1182 -0
- data/guides/source/active_record_validations_callbacks.textile +3 -3
- data/guides/source/active_support_core_extensions.textile +2 -2
- data/guides/source/asset_pipeline.textile +7 -5
- data/guides/source/association_basics.textile +2 -4
- data/guides/source/command_line.textile +1 -1
- data/guides/source/configuring.textile +4 -2
- data/guides/source/contributing_to_ruby_on_rails.textile +6 -6
- data/guides/source/initialization.textile +2 -2
- data/guides/source/performance_testing.textile +1 -1
- data/guides/source/routing.textile +1 -1
- data/guides/source/security.textile +2 -2
- data/lib/rails/commands/server.rb +1 -1
- data/lib/rails/engine.rb +1 -1
- data/lib/rails/generators/app_base.rb +2 -1
- data/lib/rails/generators/base.rb +3 -3
- data/lib/rails/generators/rails/app/templates/gitignore +15 -5
- data/lib/rails/rack.rb +0 -1
- data/lib/rails/tasks/documentation.rake +7 -7
- data/lib/rails/tasks/misc.rake +0 -2
- data/lib/rails/test_unit/testing.rake +2 -0
- data/lib/rails/version.rb +2 -2
- metadata +495 -326
- data/CHANGELOG +0 -2371
- data/lib/rails/rack/content_length.rb +0 -38
@@ -0,0 +1,1980 @@
|
|
1
|
+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
|
2
|
+
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
3
|
+
|
4
|
+
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
5
|
+
<head>
|
6
|
+
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
7
|
+
|
8
|
+
<title>Ruby on Rails Guides: Getting Started with Rails</title>
|
9
|
+
|
10
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
|
11
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
|
12
|
+
|
13
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
|
14
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
|
15
|
+
|
16
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
|
17
|
+
</head>
|
18
|
+
<body class="guide">
|
19
|
+
<div id="topNav">
|
20
|
+
<div class="wrapper">
|
21
|
+
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
|
22
|
+
<a href="http://rubyonrails.org/">Overview</a> |
|
23
|
+
<a href="http://rubyonrails.org/download">Download</a> |
|
24
|
+
<a href="http://rubyonrails.org/deploy">Deploy</a> |
|
25
|
+
<a href="https://github.com/rails/rails">Code</a> |
|
26
|
+
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
|
27
|
+
<a href="http://rubyonrails.org/documentation">Documentation</a> |
|
28
|
+
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
|
29
|
+
<a href="http://rubyonrails.org/community">Community</a> |
|
30
|
+
<a href="http://weblog.rubyonrails.org/">Blog</a>
|
31
|
+
</div>
|
32
|
+
</div>
|
33
|
+
<div id="header">
|
34
|
+
<div class="wrapper clearfix">
|
35
|
+
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
|
36
|
+
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
|
37
|
+
<ul class="nav">
|
38
|
+
<li><a href="index.html">Home</a></li>
|
39
|
+
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a>
|
40
|
+
<div id="guides" class="clearfix" style="display: none;">
|
41
|
+
<hr />
|
42
|
+
<dl class="L">
|
43
|
+
<dt>Start Here</dt>
|
44
|
+
<dd><a href="getting_started.html">Getting Started with Rails</a></dd>
|
45
|
+
<dt>Models</dt>
|
46
|
+
<dd><a href="migrations.html">Rails Database Migrations</a></dd>
|
47
|
+
<dd><a href="active_record_validations_callbacks.html">Active Record Validations and Callbacks</a></dd>
|
48
|
+
<dd><a href="association_basics.html">Active Record Associations</a></dd>
|
49
|
+
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
|
50
|
+
<dt>Views</dt>
|
51
|
+
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
|
52
|
+
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
|
53
|
+
<dt>Controllers</dt>
|
54
|
+
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
|
55
|
+
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
|
56
|
+
</dl>
|
57
|
+
<dl class="R">
|
58
|
+
<dt>Digging Deeper</dt>
|
59
|
+
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
|
60
|
+
<dd><a href="i18n.html">Rails Internationalization API</a></dd>
|
61
|
+
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
|
62
|
+
<dd><a href="testing.html">Testing Rails Applications</a></dd>
|
63
|
+
<dd><a href="security.html">Securing Rails Applications</a></dd>
|
64
|
+
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
|
65
|
+
<dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd>
|
66
|
+
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
|
67
|
+
<dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
|
68
|
+
<dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
|
69
|
+
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
|
70
|
+
|
71
|
+
<dt>Extending Rails</dt>
|
72
|
+
<dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
|
73
|
+
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
|
74
|
+
<dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
|
75
|
+
|
76
|
+
<dt>Contributing to Ruby on Rails</dt>
|
77
|
+
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
|
78
|
+
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
|
79
|
+
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
|
80
|
+
|
81
|
+
<dt>Release Notes</dt>
|
82
|
+
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
|
83
|
+
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
|
84
|
+
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
|
85
|
+
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
|
86
|
+
</dl>
|
87
|
+
</div>
|
88
|
+
</li>
|
89
|
+
<li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
|
90
|
+
<li><a href="credits.html">Credits</a></li>
|
91
|
+
</ul>
|
92
|
+
</div>
|
93
|
+
</div>
|
94
|
+
<hr class="hide" />
|
95
|
+
|
96
|
+
<div id="feature">
|
97
|
+
<div class="wrapper">
|
98
|
+
<h2>Getting Started with Rails</h2>
|
99
|
+
<p>This guide covers getting up and running with Ruby on Rails. After reading it,
|
100
|
+
you should be familiar with:</p>
|
101
|
+
<ul>
|
102
|
+
<li>Installing Rails, creating a new Rails application, and connecting your application to a database</li>
|
103
|
+
<li>The general layout of a Rails application</li>
|
104
|
+
<li>The basic principles of <span class="caps">MVC</span> (Model, View Controller) and RESTful design</li>
|
105
|
+
<li>How to quickly generate the starting pieces of a Rails application</li>
|
106
|
+
</ul>
|
107
|
+
|
108
|
+
<div id="subCol">
|
109
|
+
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
|
110
|
+
<ol class="chapters">
|
111
|
+
<li><a href="#guide-assumptions">Guide Assumptions</a></li><li><a href="#what-is-rails">What is Rails?</a><ul><li><a href="#the-mvc-architecture">The <span class="caps">MVC</span> Architecture</a></li> <li><a href="#the-components-of-rails">The Components of Rails</a></li> <li><a href="#rest"><span class="caps">REST</span></a></li></ul></li><li><a href="#creating-a-new-rails-project">Creating a New Rails Project</a><ul><li><a href="#installing-rails">Installing Rails</a></li> <li><a href="#creating-the-blog-application">Creating the Blog Application</a></li> <li><a href="#configuring-a-database">Configuring a Database</a></li> <li><a href="#creating-the-database">Creating the Database</a></li></ul></li><li><a href="#hello-rails">Hello, Rails!</a><ul><li><a href="#starting-up-the-web-server">Starting up the Web Server</a></li> <li><a href="#say-hello-rails">Say “Hello”, Rails</a></li> <li><a href="#setting-the-application-home-page">Setting the Application Home Page</a></li></ul></li><li><a href="#getting-up-and-running-quickly-with-scaffolding">Getting Up and Running Quickly with Scaffolding</a></li><li><a href="#creating-a-resource">Creating a Resource</a><ul><li><a href="#running-a-migration">Running a Migration</a></li> <li><a href="#adding-a-link">Adding a Link</a></li> <li><a href="#working-with-posts-in-the-browser">Working with Posts in the Browser</a></li> <li><a href="#the-model">The Model</a></li> <li><a href="#adding-some-validation">Adding Some Validation</a></li> <li><a href="#using-the-console">Using the Console</a></li> <li><a href="#listing-all-posts">Listing All Posts</a></li> <li><a href="#customizing-the-layout">Customizing the Layout</a></li> <li><a href="#creating-new-posts">Creating New Posts</a></li> <li><a href="#showing-an-individual-post">Showing an Individual Post</a></li> <li><a href="#editing-posts">Editing Posts</a></li> <li><a href="#destroying-a-post">Destroying a Post</a></li></ul></li><li><a href="#adding-a-second-model">Adding a Second Model</a><ul><li><a href="#generating-a-model">Generating a Model</a></li> <li><a href="#associating-models">Associating Models</a></li> <li><a href="#adding-a-route-for-comments">Adding a Route for Comments</a></li> <li><a href="#generating-a-controller">Generating a Controller</a></li></ul></li><li><a href="#refactoring">Refactoring</a><ul><li><a href="#rendering-partial-collections">Rendering Partial Collections</a></li> <li><a href="#rendering-a-partial-form">Rendering a Partial Form</a></li></ul></li><li><a href="#deleting-comments">Deleting Comments</a><ul><li><a href="#deleting-associated-objects">Deleting Associated Objects</a></li></ul></li><li><a href="#security">Security</a></li><li><a href="#building-a-multi-model-form">Building a Multi-Model Form</a></li><li><a href="#view-helpers">View Helpers</a></li><li><a href="#what-s-next">What’s Next?</a></li><li><a href="#configuration-gotchas">Configuration Gotchas</a></li></ol></div>
|
112
|
+
</div>
|
113
|
+
</div>
|
114
|
+
|
115
|
+
<div id="container">
|
116
|
+
<div class="wrapper">
|
117
|
+
<div id="mainCol">
|
118
|
+
<div class="warning"><p>This Guide is based on Rails 3.1. Some of the code shown here will not
|
119
|
+
work in earlier versions of Rails.</p></div>
|
120
|
+
<h3 id="guide-assumptions">1 Guide Assumptions</h3>
|
121
|
+
<p>This guide is designed for beginners who want to get started with a Rails
|
122
|
+
application from scratch. It does not assume that you have any prior experience
|
123
|
+
with Rails. However, to get the most out of it, you need to have some
|
124
|
+
prerequisites installed:</p>
|
125
|
+
<ul>
|
126
|
+
<li>The <a href="http://www.ruby-lang.org/en/downloads">Ruby</a> language version 1.8.7 or higher</li>
|
127
|
+
</ul>
|
128
|
+
<div class="info"><p>Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails
|
129
|
+
3.0. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02
|
130
|
+
though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults
|
131
|
+
on Rails 3.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 for smooth
|
132
|
+
sailing.</p></div>
|
133
|
+
<ul>
|
134
|
+
<li>The <a href="http://rubyforge.org/frs/?group_id=126">RubyGems</a> packaging system
|
135
|
+
<ul>
|
136
|
+
<li>If you want to learn more about RubyGems, please read the <a href="http://docs.rubygems.org/read/book/1">RubyGems User Guide</a></li>
|
137
|
+
</ul></li>
|
138
|
+
<li>A working installation of the <a href="http://www.sqlite.org">SQLite3 Database</a></li>
|
139
|
+
</ul>
|
140
|
+
<p>Rails is a web application framework running on the Ruby programming language.
|
141
|
+
If you have no prior experience with Ruby, you will find a very steep learning
|
142
|
+
curve diving straight into Rails. There are some good free resources on the
|
143
|
+
internet for learning Ruby, including:</p>
|
144
|
+
<ul>
|
145
|
+
<li><a href="http://www.humblelittlerubybook.com">Mr. Neighborly’s Humble Little Ruby Book</a></li>
|
146
|
+
<li><a href="http://www.ruby-doc.org/docs/ProgrammingRuby/">Programming Ruby</a></li>
|
147
|
+
<li><a href="http://mislav.uniqpath.com/poignant-guide/">Why’s (Poignant) Guide to Ruby</a></li>
|
148
|
+
</ul>
|
149
|
+
<p>Also, the example code for this guide is available in the rails github:https://github.com/rails/rails repository
|
150
|
+
in rails/railties/guides/code/getting_started.</p>
|
151
|
+
<h3 id="what-is-rails">2 What is Rails?</h3>
|
152
|
+
<p>Rails is a web application development framework written in the Ruby language.
|
153
|
+
It is designed to make programming web applications easier by making assumptions
|
154
|
+
about what every developer needs to get started. It allows you to write less
|
155
|
+
code while accomplishing more than many other languages and frameworks.
|
156
|
+
Experienced Rails developers also report that it makes web application
|
157
|
+
development more fun.</p>
|
158
|
+
<p>Rails is opinionated software. It makes the assumption that there is a “best”
|
159
|
+
way to do things, and it’s designed to encourage that way – and in some cases to
|
160
|
+
discourage alternatives. If you learn “The Rails Way” you’ll probably discover a
|
161
|
+
tremendous increase in productivity. If you persist in bringing old habits from
|
162
|
+
other languages to your Rails development, and trying to use patterns you
|
163
|
+
learned elsewhere, you may have a less happy experience.</p>
|
164
|
+
<p>The Rails philosophy includes several guiding principles:</p>
|
165
|
+
<ul>
|
166
|
+
<li><span class="caps">DRY</span> – “Don’t Repeat Yourself” – suggests that writing the same code over and over again is a bad thing.</li>
|
167
|
+
<li>Convention Over Configuration – means that Rails makes assumptions about what you want to do and how you’re going to
|
168
|
+
do it, rather than requiring you to specify every little thing through endless configuration files.</li>
|
169
|
+
<li><span class="caps">REST</span> is the best pattern for web applications – organizing your application around resources and standard <span class="caps">HTTP</span> verbs
|
170
|
+
is the fastest way to go.</li>
|
171
|
+
</ul>
|
172
|
+
<h4 id="the-mvc-architecture">2.1 The <span class="caps">MVC</span> Architecture</h4>
|
173
|
+
<p>At the core of Rails is the Model, View, Controller architecture, usually just
|
174
|
+
called <span class="caps">MVC</span>. <span class="caps">MVC</span> benefits include:</p>
|
175
|
+
<ul>
|
176
|
+
<li>Isolation of business logic from the user interface</li>
|
177
|
+
<li>Ease of keeping code <span class="caps">DRY</span></li>
|
178
|
+
<li>Making it clear where different types of code belong for easier maintenance</li>
|
179
|
+
</ul>
|
180
|
+
<h5 id="models">2.1.1 Models</h5>
|
181
|
+
<p>A model represents the information (data) of the application and the rules to
|
182
|
+
manipulate that data. In the case of Rails, models are primarily used for
|
183
|
+
managing the rules of interaction with a corresponding database table. In most
|
184
|
+
cases, each table in your database will correspond to one model in your
|
185
|
+
application. The bulk of your application’s business logic will be concentrated
|
186
|
+
in the models.</p>
|
187
|
+
<h5 id="views">2.1.2 Views</h5>
|
188
|
+
<p>Views represent the user interface of your application. In Rails, views are
|
189
|
+
often <span class="caps">HTML</span> files with embedded Ruby code that perform tasks related solely to
|
190
|
+
the presentation of the data. Views handle the job of providing data to the web
|
191
|
+
browser or other tool that is used to make requests from your application.</p>
|
192
|
+
<h5 id="controllers">2.1.3 Controllers</h5>
|
193
|
+
<p>Controllers provide the “glue” between models and views. In Rails, controllers
|
194
|
+
are responsible for processing the incoming requests from the web browser,
|
195
|
+
interrogating the models for data, and passing that data on to the views for
|
196
|
+
presentation.</p>
|
197
|
+
<h4 id="the-components-of-rails">2.2 The Components of Rails</h4>
|
198
|
+
<p>Rails ships as many individual components. Each of these components are briefly
|
199
|
+
explained below. If you are new to Rails, as you read this section, don’t get
|
200
|
+
hung up on the details of each component, as they will be explained in further
|
201
|
+
detail later. For instance, we will bring up Rack applications, but you don’t
|
202
|
+
need to know anything about them to continue with this guide.</p>
|
203
|
+
<ul>
|
204
|
+
<li>Action Pack
|
205
|
+
<ul>
|
206
|
+
<li>Action Controller</li>
|
207
|
+
<li>Action Dispatch</li>
|
208
|
+
<li>Action View</li>
|
209
|
+
</ul></li>
|
210
|
+
<li>Action Mailer</li>
|
211
|
+
<li>Active Model</li>
|
212
|
+
<li>Active Record</li>
|
213
|
+
<li>Active Resource</li>
|
214
|
+
<li>Active Support</li>
|
215
|
+
<li>Railties</li>
|
216
|
+
</ul>
|
217
|
+
<h5 id="action-pack">2.2.1 Action Pack</h5>
|
218
|
+
<p>Action Pack is a single gem that contains Action Controller, Action View and
|
219
|
+
Action Dispatch. The “VC” part of “<span class="caps">MVC</span>”.</p>
|
220
|
+
<h6 id="action-controller">2.2.1.1 Action Controller</h6>
|
221
|
+
<p>Action Controller is the component that manages the controllers in a Rails
|
222
|
+
application. The Action Controller framework processes incoming requests to a
|
223
|
+
Rails application, extracts parameters, and dispatches them to the intended
|
224
|
+
action. Services provided by Action Controller include session management,
|
225
|
+
template rendering, and redirect management.</p>
|
226
|
+
<h6 id="action-view">2.2.1.2 Action View</h6>
|
227
|
+
<p>Action View manages the views of your Rails application. It can create both <span class="caps">HTML</span>
|
228
|
+
and <span class="caps">XML</span> output by default. Action View manages rendering templates, including
|
229
|
+
nested and partial templates, and includes built-in <span class="caps">AJAX</span> support. View
|
230
|
+
templates are covered in more detail in another guide called <a href="layouts_and_rendering.html">Layouts and
|
231
|
+
Rendering</a>.</p>
|
232
|
+
<h6 id="action-dispatch">2.2.1.3 Action Dispatch</h6>
|
233
|
+
<p>Action Dispatch handles routing of web requests and dispatches them as you want,
|
234
|
+
either to your application or any other Rack application. Rack applications are
|
235
|
+
a more advanced topic and are covered in a separate guide called <a href="rails_on_rack.html">Rails on
|
236
|
+
Rack</a>.</p>
|
237
|
+
<h5 id="action-mailer">2.2.2 Action Mailer</h5>
|
238
|
+
<p>Action Mailer is a framework for building e-mail services. You can use Action
|
239
|
+
Mailer to receive and process incoming email and send simple plain text or
|
240
|
+
complex multipart emails based on flexible templates.</p>
|
241
|
+
<h5 id="active-model">2.2.3 Active Model</h5>
|
242
|
+
<p>Active Model provides a defined interface between the Action Pack gem services
|
243
|
+
and Object Relationship Mapping gems such as Active Record. Active Model allows
|
244
|
+
Rails to utilize other <span class="caps">ORM</span> frameworks in place of Active Record if your
|
245
|
+
application needs this.</p>
|
246
|
+
<h5 id="active-record">2.2.4 Active Record</h5>
|
247
|
+
<p>Active Record is the base for the models in a Rails application. It provides
|
248
|
+
database independence, basic <span class="caps">CRUD</span> functionality, advanced finding capabilities,
|
249
|
+
and the ability to relate models to one another, among other services.</p>
|
250
|
+
<h5 id="active-resource">2.2.5 Active Resource</h5>
|
251
|
+
<p>Active Resource provides a framework for managing the connection between
|
252
|
+
business objects and RESTful web services. It implements a way to map web-based
|
253
|
+
resources to local objects with <span class="caps">CRUD</span> semantics.</p>
|
254
|
+
<h5 id="active-support">2.2.6 Active Support</h5>
|
255
|
+
<p>Active Support is an extensive collection of utility classes and standard Ruby
|
256
|
+
library extensions that are used in Rails, both by the core code and by your
|
257
|
+
applications.</p>
|
258
|
+
<h5 id="railties">2.2.7 Railties</h5>
|
259
|
+
<p>Railties is the core Rails code that builds new Rails applications and glues the
|
260
|
+
various frameworks and plugins together in any Rails application.</p>
|
261
|
+
<h4 id="rest">2.3 <span class="caps">REST</span></h4>
|
262
|
+
<p>Rest stands for Representational State Transfer and is the foundation of the
|
263
|
+
RESTful architecture. This is generally considered to be Roy Fielding’s doctoral
|
264
|
+
thesis, <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm">Architectural Styles and the Design of Network-based Software
|
265
|
+
Architectures</a>. While
|
266
|
+
you can read through the thesis, <span class="caps">REST</span> in terms of Rails boils down to two main
|
267
|
+
principles:</p>
|
268
|
+
<ul>
|
269
|
+
<li>Using resource identifiers such as URLs to represent resources.</li>
|
270
|
+
<li>Transferring representations of the state of that resource between system components.</li>
|
271
|
+
</ul>
|
272
|
+
<p>For example, the following <span class="caps">HTTP</span> request:</p>
|
273
|
+
<p><tt><span class="caps">DELETE</span> /photos/17</tt></p>
|
274
|
+
<p>would be understood to refer to a photo resource with the ID of 17, and to
|
275
|
+
indicate a desired action – deleting that resource. <span class="caps">REST</span> is a natural style for
|
276
|
+
the architecture of web applications, and Rails hooks into this shielding you
|
277
|
+
from many of the RESTful complexities and browser quirks.</p>
|
278
|
+
<p>If you’d like more details on <span class="caps">REST</span> as an architectural style, these resources
|
279
|
+
are more approachable than Fielding’s thesis:</p>
|
280
|
+
<ul>
|
281
|
+
<li><a href="http://www.infoq.com/articles/rest-introduction">A Brief Introduction to <span class="caps">REST</span></a> by Stefan Tilkov</li>
|
282
|
+
<li><a href="http://bitworking.org/news/373/An-Introduction-to-REST">An Introduction to <span class="caps">REST</span></a> (video tutorial) by Joe Gregorio</li>
|
283
|
+
<li><a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">Representational State Transfer</a> article in Wikipedia</li>
|
284
|
+
<li><a href="http://www.infoq.com/articles/webber-rest-workflow">How to <span class="caps">GET</span> a Cup of Coffee</a> by Jim Webber, Savas Parastatidis &
|
285
|
+
Ian Robinson</li>
|
286
|
+
</ul>
|
287
|
+
<h3 id="creating-a-new-rails-project">3 Creating a New Rails Project</h3>
|
288
|
+
<p>If you follow this guide, you’ll create a Rails project called <tt>blog</tt>, a
|
289
|
+
(very) simple weblog. Before you can start building the application, you need to
|
290
|
+
make sure that you have Rails itself installed.</p>
|
291
|
+
<div class="info"><p>The examples below use # and $ to denote terminal prompts. If you are using Windows, your prompt will look something like c:\source_code></p></div>
|
292
|
+
<h4 id="installing-rails">3.1 Installing Rails</h4>
|
293
|
+
<p>In most cases, the easiest way to install Rails is to take advantage of RubyGems:</p>
|
294
|
+
<div class="code_container">
|
295
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
296
|
+
Usually run this as the root user:
|
297
|
+
# gem install rails
|
298
|
+
</pre>
|
299
|
+
</div>
|
300
|
+
<div class="info"><p>If you’re working on Windows, you can quickly install Ruby and Rails with
|
301
|
+
<a href="http://railsinstaller.org">Rails Installer</a>.</p></div>
|
302
|
+
<h4 id="creating-the-blog-application">3.2 Creating the Blog Application</h4>
|
303
|
+
<p>The best way to use this guide is to follow each step as it happens, no code or
|
304
|
+
step needed to make this example application has been left out, so you can
|
305
|
+
literally follow along step by step. If you need to see the completed code, you
|
306
|
+
can download it from <a href="https://github.com/mikel/getting-started-code">Getting Started
|
307
|
+
Code</a>.</p>
|
308
|
+
<p>To begin, open a terminal, navigate to a folder where you have rights to create
|
309
|
+
files, and type:</p>
|
310
|
+
<div class="code_container">
|
311
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
312
|
+
$ rails new blog
|
313
|
+
</pre>
|
314
|
+
</div>
|
315
|
+
<p>This will create a Rails application called Blog in a directory called blog.</p>
|
316
|
+
<div class="info"><p>You can see all of the switches that the Rails application builder accepts
|
317
|
+
by running
|
318
|
+
<tt>rails new -h</tt>.</p></div>
|
319
|
+
<p>After you create the blog application, switch to its folder to continue work
|
320
|
+
directly in that application:</p>
|
321
|
+
<div class="code_container">
|
322
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
323
|
+
$ cd blog
|
324
|
+
</pre>
|
325
|
+
</div>
|
326
|
+
<p>In any case, Rails will create a folder in your working directory called
|
327
|
+
<tt>blog</tt>. Open up that folder and explore its contents. Most of the work in
|
328
|
+
this tutorial will happen in the <tt>app/</tt> folder, but here’s a basic
|
329
|
+
rundown on the function of each folder that Rails creates in a new application
|
330
|
+
by default:</p>
|
331
|
+
<table>
|
332
|
+
<tr>
|
333
|
+
<th>File/Folder</th>
|
334
|
+
<th>Purpose</th>
|
335
|
+
</tr>
|
336
|
+
<tr>
|
337
|
+
<td>Gemfile</td>
|
338
|
+
<td>This file allows you to specify what gem dependencies are needed for your Rails application. See section on Bundler, below.</td>
|
339
|
+
</tr>
|
340
|
+
<tr>
|
341
|
+
<td><span class="caps">README</span></td>
|
342
|
+
<td>This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.</td>
|
343
|
+
</tr>
|
344
|
+
<tr>
|
345
|
+
<td>Rakefile</td>
|
346
|
+
<td>This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.</td>
|
347
|
+
</tr>
|
348
|
+
<tr>
|
349
|
+
<td>app/</td>
|
350
|
+
<td>Contains the controllers, models, views and assets for your application. You’ll focus on this folder for the remainder of this guide.</td>
|
351
|
+
</tr>
|
352
|
+
<tr>
|
353
|
+
<td>config/</td>
|
354
|
+
<td>Configure your application’s runtime rules, routes, database, and more.</td>
|
355
|
+
</tr>
|
356
|
+
<tr>
|
357
|
+
<td>config.ru</td>
|
358
|
+
<td>Rack configuration for Rack based servers used to start the application.</td>
|
359
|
+
</tr>
|
360
|
+
<tr>
|
361
|
+
<td>db/</td>
|
362
|
+
<td>Shows your current database schema, as well as the database migrations. You’ll learn about migrations shortly.</td>
|
363
|
+
</tr>
|
364
|
+
<tr>
|
365
|
+
<td>doc/</td>
|
366
|
+
<td>In-depth documentation for your application.</td>
|
367
|
+
</tr>
|
368
|
+
<tr>
|
369
|
+
<td>lib/</td>
|
370
|
+
<td>Extended modules for your application (not covered in this guide).</td>
|
371
|
+
</tr>
|
372
|
+
<tr>
|
373
|
+
<td>log/</td>
|
374
|
+
<td>Application log files.</td>
|
375
|
+
</tr>
|
376
|
+
<tr>
|
377
|
+
<td>public/</td>
|
378
|
+
<td>The only folder seen to the world as-is. Contains the static files and compiled assets.</td>
|
379
|
+
</tr>
|
380
|
+
<tr>
|
381
|
+
<td>script/</td>
|
382
|
+
<td>Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.</td>
|
383
|
+
</tr>
|
384
|
+
<tr>
|
385
|
+
<td>test/</td>
|
386
|
+
<td>Unit tests, fixtures, and other test apparatus. These are covered in <a href="testing.html">Testing Rails Applications</a></td>
|
387
|
+
</tr>
|
388
|
+
<tr>
|
389
|
+
<td>tmp/</td>
|
390
|
+
<td>Temporary files</td>
|
391
|
+
</tr>
|
392
|
+
<tr>
|
393
|
+
<td>vendor/</td>
|
394
|
+
<td>A place for all third-party code. In a typical Rails application, this includes Ruby Gems, the Rails source code (if you install it into your project) and plugins containing additional prepackaged functionality.</td>
|
395
|
+
</tr>
|
396
|
+
</table>
|
397
|
+
<h4 id="configuring-a-database">3.3 Configuring a Database</h4>
|
398
|
+
<p>Just about every Rails application will interact with a database. The database
|
399
|
+
to use is specified in a configuration file, <tt>config/database.yml</tt>. If you open
|
400
|
+
this file in a new Rails application, you’ll see a default database
|
401
|
+
configuration using SQLite3. The file contains sections for three different
|
402
|
+
environments in which Rails can run by default:</p>
|
403
|
+
<ul>
|
404
|
+
<li>The <tt>development</tt> environment is used on your development computer as you interact manually with the application.</li>
|
405
|
+
<li>The <tt>test</tt> environment is used to run automated tests.</li>
|
406
|
+
<li>The <tt>production</tt> environment is used when you deploy your application for the world to use.</li>
|
407
|
+
</ul>
|
408
|
+
<h5 id="configuring-an-sqlite3-database">3.3.1 Configuring an SQLite3 Database</h5>
|
409
|
+
<p>Rails comes with built-in support for <a href="http://www.sqlite.org">SQLite3</a>, which is
|
410
|
+
a lightweight serverless database application. While a busy production
|
411
|
+
environment may overload SQLite, it works well for development and testing.
|
412
|
+
Rails defaults to using an SQLite database when creating a new project, but you
|
413
|
+
can always change it later.</p>
|
414
|
+
<p>Here’s the section of the default configuration file
|
415
|
+
(<tt>config/database.yml</tt>) with connection information for the development
|
416
|
+
environment:</p>
|
417
|
+
<div class="code_container">
|
418
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
419
|
+
development:
|
420
|
+
adapter: sqlite3
|
421
|
+
database: db/development.sqlite3
|
422
|
+
pool: 5
|
423
|
+
timeout: 5000
|
424
|
+
</pre>
|
425
|
+
</div>
|
426
|
+
<div class="note"><p>In this guide we are using an SQLite3 database for data storage, because
|
427
|
+
it is a zero configuration database that just works. Rails also supports MySQL
|
428
|
+
and PostgreSQL “out of the box”, and has plugins for many database systems. If
|
429
|
+
you are using a database in a production environment Rails most likely has an
|
430
|
+
adapter for it.</p></div>
|
431
|
+
<h5 id="configuring-a-mysql-database">3.3.2 Configuring a MySQL Database</h5>
|
432
|
+
<p>If you choose to use MySQL instead of the shipped SQLite3 database, your
|
433
|
+
<tt>config/database.yml</tt> will look a little different. Here’s the development
|
434
|
+
section:</p>
|
435
|
+
<div class="code_container">
|
436
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
437
|
+
development:
|
438
|
+
adapter: mysql2
|
439
|
+
encoding: utf8
|
440
|
+
database: blog_development
|
441
|
+
pool: 5
|
442
|
+
username: root
|
443
|
+
password:
|
444
|
+
socket: /tmp/mysql.sock
|
445
|
+
</pre>
|
446
|
+
</div>
|
447
|
+
<p>If your development computer’s MySQL installation includes a root user with an
|
448
|
+
empty password, this configuration should work for you. Otherwise, change the
|
449
|
+
username and password in the <tt>development</tt> section as appropriate.</p>
|
450
|
+
<h5 id="configuring-a-postgresql-database">3.3.3 Configuring a PostgreSQL Database</h5>
|
451
|
+
<p>If you choose to use PostgreSQL, your <tt>config/database.yml</tt> will be customized
|
452
|
+
to use PostgreSQL databases:</p>
|
453
|
+
<div class="code_container">
|
454
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
455
|
+
development:
|
456
|
+
adapter: postgresql
|
457
|
+
encoding: unicode
|
458
|
+
database: blog_development
|
459
|
+
pool: 5
|
460
|
+
username: blog
|
461
|
+
password:
|
462
|
+
</pre>
|
463
|
+
</div>
|
464
|
+
<h5 id="configuring-an-sqlite3-database-for-jruby-platform">3.3.4 Configuring an SQLite3 Database for JRuby Platform</h5>
|
465
|
+
<p>If you choose to use SQLite3 and are using JRuby, your <tt>config/database.yml</tt> will
|
466
|
+
look a little different. Here’s the development section:</p>
|
467
|
+
<div class="code_container">
|
468
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
469
|
+
development:
|
470
|
+
adapter: jdbcsqlite3
|
471
|
+
database: db/development.sqlite3
|
472
|
+
</pre>
|
473
|
+
</div>
|
474
|
+
<h5 id="configuring-a-mysql-database-for-jruby-platform">3.3.5 Configuring a MySQL Database for JRuby Platform</h5>
|
475
|
+
<p>If you choose to use MySQL and are using JRuby, your <tt>config/database.yml</tt> will look
|
476
|
+
a little different. Here’s the development section:</p>
|
477
|
+
<div class="code_container">
|
478
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
479
|
+
development:
|
480
|
+
adapter: jdbcmysql
|
481
|
+
database: blog_development
|
482
|
+
username: root
|
483
|
+
password:
|
484
|
+
</pre>
|
485
|
+
</div>
|
486
|
+
<h5 id="configuring-a-postgresql-database-for-jruby-platform">3.3.6 Configuring a PostgreSQL Database for JRuby Platform</h5>
|
487
|
+
<p>Finally if you choose to use PostgreSQL and are using JRuby, your
|
488
|
+
<tt>config/database.yml</tt> will look a little different. Here’s the development
|
489
|
+
section:</p>
|
490
|
+
<div class="code_container">
|
491
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
492
|
+
development:
|
493
|
+
adapter: jdbcpostgresql
|
494
|
+
encoding: unicode
|
495
|
+
database: blog_development
|
496
|
+
username: blog
|
497
|
+
password:
|
498
|
+
</pre>
|
499
|
+
</div>
|
500
|
+
<p>Change the username and password in the <tt>development</tt> section as appropriate.</p>
|
501
|
+
<div class="info"><p>You don’t have to update the database configurations manually. If you look at the
|
502
|
+
options of the application generator, you will see that one of the options
|
503
|
+
is named <tt>—database</tt>. This option allows you to choose an adapter from a
|
504
|
+
list of the most used relational databases. You can even run the generator
|
505
|
+
repeatedly: <tt>cd .. && rails new blog —database=mysql</tt>. When you confirm the overwriting
|
506
|
+
of the <tt>config/database.yml</tt> file, your application will be configured for MySQL
|
507
|
+
instead of SQLite.</p></div>
|
508
|
+
<h4 id="creating-the-database">3.4 Creating the Database</h4>
|
509
|
+
<p>Now that you have your database configured, it’s time to have Rails create an
|
510
|
+
empty database for you. You can do this by running a rake command:</p>
|
511
|
+
<div class="code_container">
|
512
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
513
|
+
$ rake db:create
|
514
|
+
</pre>
|
515
|
+
</div>
|
516
|
+
<p>This will create your development and test SQLite3 databases inside the
|
517
|
+
<tt>db/</tt> folder.</p>
|
518
|
+
<div class="info"><p>Rake is a general-purpose command-runner that Rails uses for many things.
|
519
|
+
You can see the list of available rake commands in your application by running
|
520
|
+
<tt>rake -T</tt>.</p></div>
|
521
|
+
<h3 id="hello-rails">4 Hello, Rails!</h3>
|
522
|
+
<p>One of the traditional places to start with a new language is by getting some
|
523
|
+
text up on screen quickly. To do this, you need to get your Rails application
|
524
|
+
server running.</p>
|
525
|
+
<h4 id="starting-up-the-web-server">4.1 Starting up the Web Server</h4>
|
526
|
+
<p>You actually have a functional Rails application already. To see it, you need to
|
527
|
+
start a web server on your development machine. You can do this by running:</p>
|
528
|
+
<div class="code_container">
|
529
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
530
|
+
$ rails server
|
531
|
+
</pre>
|
532
|
+
</div>
|
533
|
+
<p>This will fire up an instance of the WEBrick web server by default (Rails can
|
534
|
+
also use several other web servers). To see your application in action, open a
|
535
|
+
browser window and navigate to <a href="http://localhost:3000">http://localhost:3000</a>.
|
536
|
+
You should see Rails’ default information page:</p>
|
537
|
+
<p><img src="images/rails_welcome.png" title="Welcome Aboard screenshot" alt="Welcome Aboard screenshot" /></p>
|
538
|
+
<div class="info"><p>To stop the web server, hit Ctrl+C in the terminal window where it’s
|
539
|
+
running. In development mode, Rails does not generally require you to stop the
|
540
|
+
server; changes you make in files will be automatically picked up by the server.</p></div>
|
541
|
+
<p>The “Welcome Aboard” page is the <em>smoke test</em> for a new Rails application: it
|
542
|
+
makes sure that you have your software configured correctly enough to serve a
|
543
|
+
page. You can also click on the <em>About your application’s environment</em> link to
|
544
|
+
see a summary of your application’s environment.</p>
|
545
|
+
<h4 id="say-hello-rails">4.2 Say “Hello”, Rails</h4>
|
546
|
+
<p>To get Rails saying “Hello”, you need to create at minimum a controller and a
|
547
|
+
view. Fortunately, you can do that in a single command. Enter this command in
|
548
|
+
your terminal:</p>
|
549
|
+
<div class="code_container">
|
550
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
551
|
+
$ rails generate controller home index
|
552
|
+
</pre>
|
553
|
+
</div>
|
554
|
+
<div class="info"><p>If you get a command not found error when running this command, you
|
555
|
+
need to explicitly pass Rails <tt>rails</tt> commands to Ruby: <tt>ruby
|
556
|
+
\path\to\your\application\script\rails generate controller home index</tt>.</p></div>
|
557
|
+
<p>Rails will create several files for you, including
|
558
|
+
<tt>app/views/home/index.html.erb</tt>. This is the template that will be used to
|
559
|
+
display the results of the <tt>index</tt> action (method) in the <tt>home</tt> controller.
|
560
|
+
Open this file in your text editor and edit it to contain a single line of code:</p>
|
561
|
+
<p><code class="html">
|
562
|
+
<h1>Hello, Rails!</h1>
|
563
|
+
</code></p>
|
564
|
+
<h4 id="setting-the-application-home-page">4.3 Setting the Application Home Page</h4>
|
565
|
+
<p>Now that we have made the controller and view, we need to tell Rails when we
|
566
|
+
want “Hello Rails” to show up. In our case, we want it to show up when we
|
567
|
+
navigate to the root <span class="caps">URL</span> of our site,
|
568
|
+
<a href="http://localhost:3000">http://localhost:3000</a>, instead of the “Welcome Aboard”
|
569
|
+
smoke test.</p>
|
570
|
+
<p>The first step to doing this is to delete the default page from your
|
571
|
+
application:</p>
|
572
|
+
<div class="code_container">
|
573
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
574
|
+
$ rm public/index.html
|
575
|
+
</pre>
|
576
|
+
</div>
|
577
|
+
<p>We need to do this as Rails will deliver any static file in the <tt>public</tt>
|
578
|
+
directory in preference to any dynamic content we generate from the controllers.</p>
|
579
|
+
<p>Now, you have to tell Rails where your actual home page is located. Open the
|
580
|
+
file <tt>config/routes.rb</tt> in your editor. This is your application’s <em>routing
|
581
|
+
file</em> which holds entries in a special <span class="caps">DSL</span> (domain-specific language) that tells
|
582
|
+
Rails how to connect incoming requests to controllers and actions. This file
|
583
|
+
contains many sample routes on commented lines, and one of them actually shows
|
584
|
+
you how to connect the root of your site to a specific controller and action.
|
585
|
+
Find the line beginning with <tt>root :to</tt>, uncomment it and change it like the
|
586
|
+
following:</p>
|
587
|
+
<div class="code_container">
|
588
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
589
|
+
Blog::Application.routes.draw do
|
590
|
+
|
591
|
+
#...
|
592
|
+
# You can have the root of your site routed with "root"
|
593
|
+
# just remember to delete public/index.html.
|
594
|
+
root :to => "home#index"
|
595
|
+
</pre>
|
596
|
+
</div>
|
597
|
+
<p>The <tt>root :to => "home#index"</tt> tells Rails to map the root action to the home
|
598
|
+
controller’s index action.</p>
|
599
|
+
<p>Now if you navigate to <a href="http://localhost:3000">http://localhost:3000</a> in your
|
600
|
+
browser, you’ll see <tt>Hello, Rails!</tt>.</p>
|
601
|
+
<div class="note"><p>For more information about routing, refer to <a href="routing.html">Rails Routing from the
|
602
|
+
Outside In</a>.</p></div>
|
603
|
+
<h3 id="getting-up-and-running-quickly-with-scaffolding">5 Getting Up and Running Quickly with Scaffolding</h3>
|
604
|
+
<p>Rails <em>scaffolding</em> is a quick way to generate some of the major pieces of an
|
605
|
+
application. If you want to create the models, views, and controllers for a new
|
606
|
+
resource in a single operation, scaffolding is the tool for the job.</p>
|
607
|
+
<h3 id="creating-a-resource">6 Creating a Resource</h3>
|
608
|
+
<p>In the case of the blog application, you can start by generating a scaffolded
|
609
|
+
Post resource: this will represent a single blog posting. To do this, enter this
|
610
|
+
command in your terminal:</p>
|
611
|
+
<div class="code_container">
|
612
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
613
|
+
$ rails generate scaffold Post name:string title:string content:text
|
614
|
+
</pre>
|
615
|
+
</div>
|
616
|
+
<p>The scaffold generator will build several files in your application, along with some
|
617
|
+
folders, and edit <tt>config/routes.rb</tt>. Here’s a quick overview of what it creates:</p>
|
618
|
+
<table>
|
619
|
+
<tr>
|
620
|
+
<th>File </th>
|
621
|
+
<th>Purpose</th>
|
622
|
+
</tr>
|
623
|
+
<tr>
|
624
|
+
<td>db/migrate/20100207214725_create_posts.rb </td>
|
625
|
+
<td>Migration to create the posts table in your database (your name will include a different timestamp)</td>
|
626
|
+
</tr>
|
627
|
+
<tr>
|
628
|
+
<td>app/models/post.rb </td>
|
629
|
+
<td>The Post model</td>
|
630
|
+
</tr>
|
631
|
+
<tr>
|
632
|
+
<td>test/fixtures/posts.yml </td>
|
633
|
+
<td>Dummy posts for use in testing</td>
|
634
|
+
</tr>
|
635
|
+
<tr>
|
636
|
+
<td>app/controllers/posts_controller.rb </td>
|
637
|
+
<td>The Posts controller</td>
|
638
|
+
</tr>
|
639
|
+
<tr>
|
640
|
+
<td>app/views/posts/index.html.erb </td>
|
641
|
+
<td>A view to display an index of all posts </td>
|
642
|
+
</tr>
|
643
|
+
<tr>
|
644
|
+
<td>app/views/posts/edit.html.erb </td>
|
645
|
+
<td>A view to edit an existing post</td>
|
646
|
+
</tr>
|
647
|
+
<tr>
|
648
|
+
<td>app/views/posts/show.html.erb </td>
|
649
|
+
<td>A view to display a single post</td>
|
650
|
+
</tr>
|
651
|
+
<tr>
|
652
|
+
<td>app/views/posts/new.html.erb </td>
|
653
|
+
<td>A view to create a new post</td>
|
654
|
+
</tr>
|
655
|
+
<tr>
|
656
|
+
<td>app/views/posts/_form.html.erb </td>
|
657
|
+
<td>A partial to control the overall look and feel of the form used in edit and new views</td>
|
658
|
+
</tr>
|
659
|
+
<tr>
|
660
|
+
<td>app/helpers/posts_helper.rb </td>
|
661
|
+
<td>Helper functions to be used from the post views</td>
|
662
|
+
</tr>
|
663
|
+
<tr>
|
664
|
+
<td>app/assets/stylesheets/scaffolds.css.scss </td>
|
665
|
+
<td>Cascading style sheet to make the scaffolded views look better</td>
|
666
|
+
</tr>
|
667
|
+
<tr>
|
668
|
+
<td>app/assets/stylesheets/posts.css.scss </td>
|
669
|
+
<td>Cascading style sheet for the posts controller</td>
|
670
|
+
</tr>
|
671
|
+
<tr>
|
672
|
+
<td>app/assets/javascripts/posts.js.coffee </td>
|
673
|
+
<td>CoffeeScript for the posts controller</td>
|
674
|
+
</tr>
|
675
|
+
<tr>
|
676
|
+
<td>test/unit/post_test.rb </td>
|
677
|
+
<td>Unit testing harness for the posts model</td>
|
678
|
+
</tr>
|
679
|
+
<tr>
|
680
|
+
<td>test/functional/posts_controller_test.rb </td>
|
681
|
+
<td>Functional testing harness for the posts controller</td>
|
682
|
+
</tr>
|
683
|
+
<tr>
|
684
|
+
<td>test/unit/helpers/posts_helper_test.rb </td>
|
685
|
+
<td>Unit testing harness for the posts helper</td>
|
686
|
+
</tr>
|
687
|
+
<tr>
|
688
|
+
<td>config/routes.rb </td>
|
689
|
+
<td>Edited to include routing information for posts</td>
|
690
|
+
</tr>
|
691
|
+
</table>
|
692
|
+
<div class="note"><p>While scaffolding will get you up and running quickly, the code it
|
693
|
+
generates is unlikely to be a perfect fit for your application. You’ll most
|
694
|
+
probably want to customize the generated code. Many experienced Rails developers
|
695
|
+
avoid scaffolding entirely, preferring to write all or most of their source code
|
696
|
+
from scratch. Rails, however, makes it really simple to customize templates for
|
697
|
+
generated models, controllers, views and other source files. You’ll find more
|
698
|
+
information in the <a href="generators.html">Creating and Customizing Rails Generators &
|
699
|
+
Templates</a> guide.</p></div>
|
700
|
+
<h4 id="running-a-migration">6.1 Running a Migration</h4>
|
701
|
+
<p>One of the products of the <tt>rails generate scaffold</tt> command is a <em>database
|
702
|
+
migration</em>. Migrations are Ruby classes that are designed to make it simple to
|
703
|
+
create and modify database tables. Rails uses rake commands to run migrations,
|
704
|
+
and it’s possible to undo a migration after it’s been applied to your database.
|
705
|
+
Migration filenames include a timestamp to ensure that they’re processed in the
|
706
|
+
order that they were created.</p>
|
707
|
+
<p>If you look in the <tt>db/migrate/20100207214725_create_posts.rb</tt> file (remember,
|
708
|
+
yours will have a slightly different name), here’s what you’ll find:</p>
|
709
|
+
<div class="code_container">
|
710
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
711
|
+
class CreatePosts < ActiveRecord::Migration
|
712
|
+
def change
|
713
|
+
create_table :posts do |t|
|
714
|
+
t.string :name
|
715
|
+
t.string :title
|
716
|
+
t.text :content
|
717
|
+
|
718
|
+
t.timestamps
|
719
|
+
end
|
720
|
+
end
|
721
|
+
end
|
722
|
+
</pre>
|
723
|
+
</div>
|
724
|
+
<p>The above migration creates a method named <tt>change</tt> which will be called when you
|
725
|
+
run this migration. The action defined in that method is also reversible, which
|
726
|
+
means Rails knows how to reverse the change made by this migration, in case you
|
727
|
+
want to reverse it at later date. By default, when you run this migration it
|
728
|
+
creates a <tt>posts</tt> table with two string columns and a text column. It also
|
729
|
+
creates two timestamp fields to track record creation and updating. More
|
730
|
+
information about Rails migrations can be found in the <a href="migrations.html">Rails Database
|
731
|
+
Migrations</a> guide.</p>
|
732
|
+
<p>At this point, you can use a rake command to run the migration:</p>
|
733
|
+
<div class="code_container">
|
734
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
735
|
+
$ rake db:migrate
|
736
|
+
</pre>
|
737
|
+
</div>
|
738
|
+
<p>Rails will execute this migration command and tell you it created the Posts
|
739
|
+
table.</p>
|
740
|
+
<div class="code_container">
|
741
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
742
|
+
== CreatePosts: migrating ====================================================
|
743
|
+
-- create_table(:posts)
|
744
|
+
-> 0.0019s
|
745
|
+
== CreatePosts: migrated (0.0020s) ===========================================
|
746
|
+
</pre>
|
747
|
+
</div>
|
748
|
+
<div class="note"><p>Because by default you’re working in the development environment, this
|
749
|
+
command will apply to the database defined in the <tt>development</tt> section of your
|
750
|
+
<tt>config/database.yml</tt> file. If you would like to execute migrations in another
|
751
|
+
environment, for instance in production, you must explicitly pass it when
|
752
|
+
invoking the command: <tt>rake db:migrate RAILS_ENV=production</tt>.</p></div>
|
753
|
+
<h4 id="adding-a-link">6.2 Adding a Link</h4>
|
754
|
+
<p>To hook the posts up to the home page you’ve already created, you can add a link
|
755
|
+
to the home page. Open <tt>app/views/home/index.html.erb</tt> and modify it as follows:</p>
|
756
|
+
<div class="code_container">
|
757
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
758
|
+
<h1>Hello, Rails!</h1>
|
759
|
+
<%= link_to "My Blog", posts_path %>
|
760
|
+
</pre>
|
761
|
+
</div>
|
762
|
+
<p>The <tt>link_to</tt> method is one of Rails’ built-in view helpers. It creates a
|
763
|
+
hyperlink based on text to display and where to go – in this case, to the path
|
764
|
+
for posts.</p>
|
765
|
+
<h4 id="working-with-posts-in-the-browser">6.3 Working with Posts in the Browser</h4>
|
766
|
+
<p>Now you’re ready to start working with posts. To do that, navigate to
|
767
|
+
<a href="http://localhost:3000/">http://localhost:3000</a> and then click the “My Blog”
|
768
|
+
link:</p>
|
769
|
+
<p><img src="images/posts_index.png" title="Posts Index screenshot" alt="Posts Index screenshot" /></p>
|
770
|
+
<p>This is the result of Rails rendering the <tt>index</tt> view of your posts. There
|
771
|
+
aren’t currently any posts in the database, but if you click the <tt>New Post</tt> link
|
772
|
+
you can create one. After that, you’ll find that you can edit posts, look at
|
773
|
+
their details, or destroy them. All of the logic and <span class="caps">HTML</span> to handle this was
|
774
|
+
built by the single <tt>rails generate scaffold</tt> command.</p>
|
775
|
+
<div class="info"><p>In development mode (which is what you’re working in by default), Rails
|
776
|
+
reloads your application with every browser request, so there’s no need to stop
|
777
|
+
and restart the web server.</p></div>
|
778
|
+
<p>Congratulations, you’re riding the rails! Now it’s time to see how it all works.</p>
|
779
|
+
<h4 id="the-model">6.4 The Model</h4>
|
780
|
+
<p>The model file, <tt>app/models/post.rb</tt> is about as simple as it can get:</p>
|
781
|
+
<div class="code_container">
|
782
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
783
|
+
class Post < ActiveRecord::Base
|
784
|
+
end
|
785
|
+
</pre>
|
786
|
+
</div>
|
787
|
+
<p>There isn’t much to this file – but note that the <tt>Post</tt> class inherits from
|
788
|
+
<tt>ActiveRecord::Base</tt>. Active Record supplies a great deal of functionality to
|
789
|
+
your Rails models for free, including basic database <span class="caps">CRUD</span> (Create, Read, Update,
|
790
|
+
Destroy) operations, data validation, as well as sophisticated search support
|
791
|
+
and the ability to relate multiple models to one another.</p>
|
792
|
+
<h4 id="adding-some-validation">6.5 Adding Some Validation</h4>
|
793
|
+
<p>Rails includes methods to help you validate the data that you send to models.
|
794
|
+
Open the <tt>app/models/post.rb</tt> file and edit it:</p>
|
795
|
+
<div class="code_container">
|
796
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
797
|
+
class Post < ActiveRecord::Base
|
798
|
+
validates :name, :presence => true
|
799
|
+
validates :title, :presence => true,
|
800
|
+
:length => { :minimum => 5 }
|
801
|
+
end
|
802
|
+
</pre>
|
803
|
+
</div>
|
804
|
+
<p>These changes will ensure that all posts have a name and a title, and that the
|
805
|
+
title is at least five characters long. Rails can validate a variety of
|
806
|
+
conditions in a model, including the presence or uniqueness of columns, their
|
807
|
+
format, and the existence of associated objects.</p>
|
808
|
+
<h4 id="using-the-console">6.6 Using the Console</h4>
|
809
|
+
<p>To see your validations in action, you can use the console. The console is a
|
810
|
+
command-line tool that lets you execute Ruby code in the context of your
|
811
|
+
application:</p>
|
812
|
+
<div class="code_container">
|
813
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
814
|
+
$ rails console
|
815
|
+
</pre>
|
816
|
+
</div>
|
817
|
+
<div class="info"><p>The default console will make changes to your database. You can instead
|
818
|
+
open a console that will roll back any changes you make by using <tt>rails console
|
819
|
+
—sandbox</tt>.</p></div>
|
820
|
+
<p>After the console loads, you can use it to work with your application’s models:</p>
|
821
|
+
<div class="code_container">
|
822
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
823
|
+
>> p = Post.new(:content => "A new post")
|
824
|
+
=> #<Post id: nil, name: nil, title: nil,
|
825
|
+
content: "A new post", created_at: nil,
|
826
|
+
updated_at: nil>
|
827
|
+
>> p.save
|
828
|
+
=> false
|
829
|
+
>> p.errors
|
830
|
+
=> #<OrderedHash { :title=>["can't be blank",
|
831
|
+
"is too short (minimum is 5 characters)"],
|
832
|
+
:name=>["can't be blank"] }>
|
833
|
+
</pre>
|
834
|
+
</div>
|
835
|
+
<p>This code shows creating a new <tt>Post</tt> instance, attempting to save it and
|
836
|
+
getting <tt>false</tt> for a return value (indicating that the save failed), and
|
837
|
+
inspecting the <tt>errors</tt> of the post.</p>
|
838
|
+
<p>When you’re finished, type <tt>exit</tt> and hit <tt>return</tt> to exit the console.</p>
|
839
|
+
<div class="info"><p>Unlike the development web server, the console does not automatically load
|
840
|
+
your code afresh for each line. If you make changes to your models while the
|
841
|
+
console is open, type <tt>reload!</tt> at the console prompt to load them.</p></div>
|
842
|
+
<h4 id="listing-all-posts">6.7 Listing All Posts</h4>
|
843
|
+
<p>The easiest place to start looking at functionality is with the code that lists
|
844
|
+
all posts. Open the file <tt>app/controllers/posts_controller.rb</tt> and look at the
|
845
|
+
<tt>index</tt> action:</p>
|
846
|
+
<div class="code_container">
|
847
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
848
|
+
def index
|
849
|
+
@posts = Post.all
|
850
|
+
|
851
|
+
respond_to do |format|
|
852
|
+
format.html # index.html.erb
|
853
|
+
format.json { render :json => @posts }
|
854
|
+
end
|
855
|
+
end
|
856
|
+
</pre>
|
857
|
+
</div>
|
858
|
+
<p><tt>Post.all</tt> calls the <tt>Post</tt> model to return all of the posts currently in the
|
859
|
+
database. The result of this call is an array of posts that we store in an
|
860
|
+
instance variable called <tt>@posts</tt>.</p>
|
861
|
+
<div class="info"><p>For more information on finding records with Active Record, see <a href="active_record_querying.html">Active
|
862
|
+
Record Query Interface</a>.</p></div>
|
863
|
+
<p>The <tt>respond_to</tt> block handles both <span class="caps">HTML</span> and <span class="caps">JSON</span> calls to this action. If you
|
864
|
+
browse to <a href="http://localhost:3000/posts.json">http://localhost:3000/posts.json</a>,
|
865
|
+
you’ll see a <span class="caps">JSON</span> containing all of the posts. The <span class="caps">HTML</span> format looks for a view
|
866
|
+
in <tt>app/views/posts/</tt> with a name that corresponds to the action name. Rails
|
867
|
+
makes all of the instance variables from the action available to the view.
|
868
|
+
Here’s <tt>app/views/posts/index.html.erb</tt>:</p>
|
869
|
+
<div class="code_container">
|
870
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
871
|
+
<h1>Listing posts</h1>
|
872
|
+
|
873
|
+
<table>
|
874
|
+
<tr>
|
875
|
+
<th>Name</th>
|
876
|
+
<th>Title</th>
|
877
|
+
<th>Content</th>
|
878
|
+
<th></th>
|
879
|
+
<th></th>
|
880
|
+
<th></th>
|
881
|
+
</tr>
|
882
|
+
|
883
|
+
<% @posts.each do |post| %>
|
884
|
+
<tr>
|
885
|
+
<td><%= post.name %></td>
|
886
|
+
<td><%= post.title %></td>
|
887
|
+
<td><%= post.content %></td>
|
888
|
+
<td><%= link_to 'Show', post %></td>
|
889
|
+
<td><%= link_to 'Edit', edit_post_path(post) %></td>
|
890
|
+
<td><%= link_to 'Destroy', post, :confirm => 'Are you sure?',
|
891
|
+
:method => :delete %></td>
|
892
|
+
</tr>
|
893
|
+
<% end %>
|
894
|
+
</table>
|
895
|
+
|
896
|
+
<br />
|
897
|
+
|
898
|
+
<%= link_to 'New post', new_post_path %>
|
899
|
+
</pre>
|
900
|
+
</div>
|
901
|
+
<p>This view iterates over the contents of the <tt>@posts</tt> array to display content
|
902
|
+
and links. A few things to note in the view:</p>
|
903
|
+
<ul>
|
904
|
+
<li><tt>link_to</tt> builds a hyperlink to a particular destination</li>
|
905
|
+
<li><tt>edit_post_path</tt> and <tt>new_post_path</tt> are helpers that Rails provides as part of RESTful routing. You’ll see a variety of these helpers for the different actions that the controller includes.</li>
|
906
|
+
</ul>
|
907
|
+
<div class="note"><p>In previous versions of Rails, you had to use <tt><%=h post.name %></tt> so
|
908
|
+
that any <span class="caps">HTML</span> would be escaped before being inserted into the page. In Rails
|
909
|
+
3.0, this is now the default. To get unescaped <span class="caps">HTML</span>, you now use <ins><%= raw
|
910
|
+
post.name %></ins>.</p></div>
|
911
|
+
<div class="info"><p>For more details on the rendering process, see <a href="layouts_and_rendering.html">Layouts and Rendering in
|
912
|
+
Rails</a>.</p></div>
|
913
|
+
<h4 id="customizing-the-layout">6.8 Customizing the Layout</h4>
|
914
|
+
<p>The view is only part of the story of how <span class="caps">HTML</span> is displayed in your web browser.
|
915
|
+
Rails also has the concept of <tt>layouts</tt>, which are containers for views. When
|
916
|
+
Rails renders a view to the browser, it does so by putting the view’s <span class="caps">HTML</span> into
|
917
|
+
a layout’s <span class="caps">HTML</span>. In previous versions of Rails, the <tt>rails generate scaffold</tt>
|
918
|
+
command would automatically create a controller specific layout, like
|
919
|
+
<tt>app/views/layouts/posts.html.erb</tt>, for the posts controller. However this has
|
920
|
+
been changed in Rails 3.0. An application specific <tt>layout</tt> is used for all the
|
921
|
+
controllers and can be found in <tt>app/views/layouts/application.html.erb</tt>. Open
|
922
|
+
this layout in your editor and modify the <tt>body</tt> tag:</p>
|
923
|
+
<div class="code_container">
|
924
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
925
|
+
<!DOCTYPE html>
|
926
|
+
<html>
|
927
|
+
<head>
|
928
|
+
<title>Blog</title>
|
929
|
+
<%= stylesheet_link_tag "application" %>
|
930
|
+
<%= javascript_include_tag "application" %>
|
931
|
+
<%= csrf_meta_tags %>
|
932
|
+
</head>
|
933
|
+
<body style="background: #EEEEEE;">
|
934
|
+
|
935
|
+
<%= yield %>
|
936
|
+
|
937
|
+
</body>
|
938
|
+
</html>
|
939
|
+
</pre>
|
940
|
+
</div>
|
941
|
+
<p>Now when you refresh the <tt>/posts</tt> page, you’ll see a gray background to the
|
942
|
+
page. This same gray background will be used throughout all the views for posts.</p>
|
943
|
+
<h4 id="creating-new-posts">6.9 Creating New Posts</h4>
|
944
|
+
<p>Creating a new post involves two actions. The first is the <tt>new</tt> action, which
|
945
|
+
instantiates an empty <tt>Post</tt> object:</p>
|
946
|
+
<div class="code_container">
|
947
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
948
|
+
def new
|
949
|
+
@post = Post.new
|
950
|
+
|
951
|
+
respond_to do |format|
|
952
|
+
format.html # new.html.erb
|
953
|
+
format.json { render :json => @post }
|
954
|
+
end
|
955
|
+
end
|
956
|
+
</pre>
|
957
|
+
</div>
|
958
|
+
<p>The <tt>new.html.erb</tt> view displays this empty Post to the user:</p>
|
959
|
+
<div class="code_container">
|
960
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
961
|
+
<h1>New post</h1>
|
962
|
+
|
963
|
+
<%= render 'form' %>
|
964
|
+
|
965
|
+
<%= link_to 'Back', posts_path %>
|
966
|
+
</pre>
|
967
|
+
</div>
|
968
|
+
<p>The <tt><%= render 'form' %></tt> line is our first introduction to <em>partials</em> in
|
969
|
+
Rails. A partial is a snippet of <span class="caps">HTML</span> and Ruby code that can be reused in
|
970
|
+
multiple locations. In this case, the form used to make a new post is basically
|
971
|
+
identical to the form used to edit a post, both having text fields for the name and
|
972
|
+
title, a text area for the content, and a button to create the new post or to update
|
973
|
+
the existing one.</p>
|
974
|
+
<p>If you take a look at <tt>views/posts/_form.html.erb</tt> file, you will see the
|
975
|
+
following:</p>
|
976
|
+
<div class="code_container">
|
977
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
978
|
+
<%= form_for(@post) do |f| %>
|
979
|
+
<% if @post.errors.any? %>
|
980
|
+
<div id="errorExplanation">
|
981
|
+
<h2><%= pluralize(@post.errors.count, "error") %> prohibited
|
982
|
+
this post from being saved:</h2>
|
983
|
+
<ul>
|
984
|
+
<% @post.errors.full_messages.each do |msg| %>
|
985
|
+
<li><%= msg %></li>
|
986
|
+
<% end %>
|
987
|
+
</ul>
|
988
|
+
</div>
|
989
|
+
<% end %>
|
990
|
+
|
991
|
+
<div class="field">
|
992
|
+
<%= f.label :name %><br />
|
993
|
+
<%= f.text_field :name %>
|
994
|
+
</div>
|
995
|
+
<div class="field">
|
996
|
+
<%= f.label :title %><br />
|
997
|
+
<%= f.text_field :title %>
|
998
|
+
</div>
|
999
|
+
<div class="field">
|
1000
|
+
<%= f.label :content %><br />
|
1001
|
+
<%= f.text_area :content %>
|
1002
|
+
</div>
|
1003
|
+
<div class="actions">
|
1004
|
+
<%= f.submit %>
|
1005
|
+
</div>
|
1006
|
+
<% end %>
|
1007
|
+
</pre>
|
1008
|
+
</div>
|
1009
|
+
<p>This partial receives all the instance variables defined in the calling view
|
1010
|
+
file. In this case, the controller assigned the new <tt>Post</tt> object to <tt>@post</tt>,
|
1011
|
+
which will thus be available in both the view and the partial as <tt>@post</tt>.</p>
|
1012
|
+
<p>For more information on partials, refer to the <a href="layouts_and_rendering.html#using-partials">Layouts and Rendering in
|
1013
|
+
Rails</a> guide.</p>
|
1014
|
+
<p>The <tt>form_for</tt> block is used to create an <span class="caps">HTML</span> form. Within this block, you have
|
1015
|
+
access to methods to build various controls on the form. For example,
|
1016
|
+
<tt>f.text_field :name</tt> tells Rails to create a text input on the form and to hook
|
1017
|
+
it up to the <tt>name</tt> attribute of the instance being displayed. You can only use
|
1018
|
+
these methods with attributes of the model that the form is based on (in this
|
1019
|
+
case <tt>name</tt>, <tt>title</tt>, and <tt>content</tt>). Rails uses <tt>form_for</tt> in preference to
|
1020
|
+
having you write raw <span class="caps">HTML</span> because the code is more succinct, and because it
|
1021
|
+
explicitly ties the form to a particular model instance.</p>
|
1022
|
+
<p>The <tt>form_for</tt> block is also smart enough to work out if you are doing a <em>New
|
1023
|
+
Post</em> or an <em>Edit Post</em> action, and will set the form <tt>action</tt> tags and submit
|
1024
|
+
button names appropriately in the <span class="caps">HTML</span> output.</p>
|
1025
|
+
<div class="info"><p>If you need to create an <span class="caps">HTML</span> form that displays arbitrary fields, not tied
|
1026
|
+
to a model, you should use the <tt>form_tag</tt> method, which provides shortcuts for
|
1027
|
+
building forms that are not necessarily tied to a model instance.</p></div>
|
1028
|
+
<p>When the user clicks the <tt>Create Post</tt> button on this form, the browser will
|
1029
|
+
send information back to the <tt>create</tt> action of the controller (Rails knows to
|
1030
|
+
call the <tt>create</tt> action because the form is sent with an <span class="caps">HTTP</span> <span class="caps">POST</span> request;
|
1031
|
+
that’s one of the conventions that were mentioned earlier):</p>
|
1032
|
+
<div class="code_container">
|
1033
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1034
|
+
def create
|
1035
|
+
@post = Post.new(params[:post])
|
1036
|
+
|
1037
|
+
respond_to do |format|
|
1038
|
+
if @post.save
|
1039
|
+
format.html { redirect_to(@post,
|
1040
|
+
:notice => 'Post was successfully created.') }
|
1041
|
+
format.json { render :json => @post,
|
1042
|
+
:status => :created, :location => @post }
|
1043
|
+
else
|
1044
|
+
format.html { render :action => "new" }
|
1045
|
+
format.json { render :json => @post.errors,
|
1046
|
+
:status => :unprocessable_entity }
|
1047
|
+
end
|
1048
|
+
end
|
1049
|
+
end
|
1050
|
+
</pre>
|
1051
|
+
</div>
|
1052
|
+
<p>The <tt>create</tt> action instantiates a new Post object from the data supplied by the
|
1053
|
+
user on the form, which Rails makes available in the <tt>params</tt> hash. After
|
1054
|
+
successfully saving the new post, <tt>create</tt> returns the appropriate format that
|
1055
|
+
the user has requested (<span class="caps">HTML</span> in our case). It then redirects the user to the
|
1056
|
+
resulting post <tt>show</tt> action and sets a notice to the user that the Post was
|
1057
|
+
successfully created.</p>
|
1058
|
+
<p>If the post was not successfully saved, due to a validation error, then the
|
1059
|
+
controller returns the user back to the <tt>new</tt> action with any error messages so
|
1060
|
+
that the user has the chance to fix the error and try again.</p>
|
1061
|
+
<p>The “Post was successfully created.” message is stored in the Rails
|
1062
|
+
<tt>flash</tt> hash (usually just called <em>the flash</em>), so that messages can be carried
|
1063
|
+
over to another action, providing the user with useful information on the status
|
1064
|
+
of their request. In the case of <tt>create</tt>, the user never actually sees any page
|
1065
|
+
rendered during the post creation process, because it immediately redirects to
|
1066
|
+
the new <tt>Post</tt> as soon as Rails saves the record. The Flash carries over a message to
|
1067
|
+
the next action, so that when the user is redirected back to the <tt>show</tt> action,
|
1068
|
+
they are presented with a message saying “Post was successfully created.”</p>
|
1069
|
+
<h4 id="showing-an-individual-post">6.10 Showing an Individual Post</h4>
|
1070
|
+
<p>When you click the <tt>show</tt> link for a post on the index page, it will bring you
|
1071
|
+
to a <span class="caps">URL</span> like <tt>http://localhost:3000/posts/1</tt>. Rails interprets this as a call
|
1072
|
+
to the <tt>show</tt> action for the resource, and passes in <tt>1</tt> as the <tt>:id</tt> parameter.
|
1073
|
+
Here’s the <tt>show</tt> action:</p>
|
1074
|
+
<div class="code_container">
|
1075
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1076
|
+
def show
|
1077
|
+
@post = Post.find(params[:id])
|
1078
|
+
|
1079
|
+
respond_to do |format|
|
1080
|
+
format.html # show.html.erb
|
1081
|
+
format.json { render :json => @post }
|
1082
|
+
end
|
1083
|
+
end
|
1084
|
+
</pre>
|
1085
|
+
</div>
|
1086
|
+
<p>The <tt>show</tt> action uses <tt>Post.find</tt> to search for a single record in the database
|
1087
|
+
by its id value. After finding the record, Rails displays it by using
|
1088
|
+
<tt>show.html.erb</tt>:</p>
|
1089
|
+
<div class="code_container">
|
1090
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1091
|
+
<p class="notice"><%= notice %></p>
|
1092
|
+
|
1093
|
+
<p>
|
1094
|
+
<b>Name:</b>
|
1095
|
+
<%= @post.name %>
|
1096
|
+
</p>
|
1097
|
+
|
1098
|
+
<p>
|
1099
|
+
<b>Title:</b>
|
1100
|
+
<%= @post.title %>
|
1101
|
+
</p>
|
1102
|
+
|
1103
|
+
<p>
|
1104
|
+
<b>Content:</b>
|
1105
|
+
<%= @post.content %>
|
1106
|
+
</p>
|
1107
|
+
|
1108
|
+
|
1109
|
+
<%= link_to 'Edit', edit_post_path(@post) %> |
|
1110
|
+
<%= link_to 'Back', posts_path %>
|
1111
|
+
</pre>
|
1112
|
+
</div>
|
1113
|
+
<h4 id="editing-posts">6.11 Editing Posts</h4>
|
1114
|
+
<p>Like creating a new post, editing a post is a two-part process. The first step
|
1115
|
+
is a request to <tt>edit_post_path(@post)</tt> with a particular post. This calls the
|
1116
|
+
<tt>edit</tt> action in the controller:</p>
|
1117
|
+
<div class="code_container">
|
1118
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1119
|
+
def edit
|
1120
|
+
@post = Post.find(params[:id])
|
1121
|
+
end
|
1122
|
+
</pre>
|
1123
|
+
</div>
|
1124
|
+
<p>After finding the requested post, Rails uses the <tt>edit.html.erb</tt> view to display
|
1125
|
+
it:</p>
|
1126
|
+
<div class="code_container">
|
1127
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1128
|
+
<h1>Editing post</h1>
|
1129
|
+
|
1130
|
+
<%= render 'form' %>
|
1131
|
+
|
1132
|
+
<%= link_to 'Show', @post %> |
|
1133
|
+
<%= link_to 'Back', posts_path %>
|
1134
|
+
</pre>
|
1135
|
+
</div>
|
1136
|
+
<p>Again, as with the <tt>new</tt> action, the <tt>edit</tt> action is using the <tt>form</tt> partial.
|
1137
|
+
This time, however, the form will do a <span class="caps">PUT</span> action to the <tt>PostsController</tt> and the
|
1138
|
+
submit button will display “Update Post”.</p>
|
1139
|
+
<p>Submitting the form created by this view will invoke the <tt>update</tt> action within
|
1140
|
+
the controller:</p>
|
1141
|
+
<div class="code_container">
|
1142
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1143
|
+
def update
|
1144
|
+
@post = Post.find(params[:id])
|
1145
|
+
|
1146
|
+
respond_to do |format|
|
1147
|
+
if @post.update_attributes(params[:post])
|
1148
|
+
format.html { redirect_to(@post,
|
1149
|
+
:notice => 'Post was successfully updated.') }
|
1150
|
+
format.json { render :json => {}, :status => :ok }
|
1151
|
+
else
|
1152
|
+
format.html { render :action => "edit" }
|
1153
|
+
format.json { render :json => @post.errors,
|
1154
|
+
:status => :unprocessable_entity }
|
1155
|
+
end
|
1156
|
+
end
|
1157
|
+
end
|
1158
|
+
</pre>
|
1159
|
+
</div>
|
1160
|
+
<p>In the <tt>update</tt> action, Rails first uses the <tt>:id</tt> parameter passed back from
|
1161
|
+
the edit view to locate the database record that’s being edited. The
|
1162
|
+
<tt>update_attributes</tt> call then takes the <tt>post</tt> parameter (a hash) from the request
|
1163
|
+
and applies it to this record. If all goes well, the user is redirected to the
|
1164
|
+
post’s <tt>show</tt> action. If there are any problems, it redirects back to the <tt>edit</tt> action to
|
1165
|
+
correct them.</p>
|
1166
|
+
<h4 id="destroying-a-post">6.12 Destroying a Post</h4>
|
1167
|
+
<p>Finally, clicking one of the <tt>destroy</tt> links sends the associated id to the
|
1168
|
+
<tt>destroy</tt> action:</p>
|
1169
|
+
<div class="code_container">
|
1170
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1171
|
+
def destroy
|
1172
|
+
@post = Post.find(params[:id])
|
1173
|
+
@post.destroy
|
1174
|
+
|
1175
|
+
respond_to do |format|
|
1176
|
+
format.html { redirect_to posts_url }
|
1177
|
+
format.json { head :ok }
|
1178
|
+
end
|
1179
|
+
end
|
1180
|
+
</pre>
|
1181
|
+
</div>
|
1182
|
+
<p>The <tt>destroy</tt> method of an Active Record model instance removes the
|
1183
|
+
corresponding record from the database. After that’s done, there isn’t any
|
1184
|
+
record to display, so Rails redirects the user’s browser to the index action of
|
1185
|
+
the controller.</p>
|
1186
|
+
<h3 id="adding-a-second-model">7 Adding a Second Model</h3>
|
1187
|
+
<p>Now that you’ve seen how a model built with scaffolding looks like, it’s time to
|
1188
|
+
add a second model to the application. The second model will handle comments on
|
1189
|
+
blog posts.</p>
|
1190
|
+
<h4 id="generating-a-model">7.1 Generating a Model</h4>
|
1191
|
+
<p>Models in Rails use a singular name, and their corresponding database tables use
|
1192
|
+
a plural name. For the model to hold comments, the convention is to use the name
|
1193
|
+
<tt>Comment</tt>. Even if you don’t want to use the entire apparatus set up by
|
1194
|
+
scaffolding, most Rails developers still use generators to make things like
|
1195
|
+
models and controllers. To create the new model, run this command in your
|
1196
|
+
terminal:</p>
|
1197
|
+
<div class="code_container">
|
1198
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
1199
|
+
$ rails generate model Comment commenter:string body:text post:references
|
1200
|
+
</pre>
|
1201
|
+
</div>
|
1202
|
+
<p>This command will generate four files:</p>
|
1203
|
+
<ul>
|
1204
|
+
<li><tt>app/models/comment.rb</tt> – The model.</li>
|
1205
|
+
<li><tt>db/migrate/20100207235629_create_comments.rb</tt> – The migration.</li>
|
1206
|
+
<li><tt>test/unit/comment_test.rb</tt> and <tt>test/fixtures/comments.yml</tt> – The test harness.</li>
|
1207
|
+
</ul>
|
1208
|
+
<p>First, take a look at <tt>comment.rb</tt>:</p>
|
1209
|
+
<div class="code_container">
|
1210
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1211
|
+
class Comment < ActiveRecord::Base
|
1212
|
+
belongs_to :post
|
1213
|
+
end
|
1214
|
+
</pre>
|
1215
|
+
</div>
|
1216
|
+
<p>This is very similar to the <tt>post.rb</tt> model that you saw earlier. The difference
|
1217
|
+
is the line <tt>belongs_to :post</tt>, which sets up an Active Record <em>association</em>.
|
1218
|
+
You’ll learn a little about associations in the next section of this guide.</p>
|
1219
|
+
<p>In addition to the model, Rails has also made a migration to create the
|
1220
|
+
corresponding database table:</p>
|
1221
|
+
<div class="code_container">
|
1222
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1223
|
+
class CreateComments < ActiveRecord::Migration
|
1224
|
+
def change
|
1225
|
+
create_table :comments do |t|
|
1226
|
+
t.string :commenter
|
1227
|
+
t.text :body
|
1228
|
+
t.references :post
|
1229
|
+
|
1230
|
+
t.timestamps
|
1231
|
+
end
|
1232
|
+
|
1233
|
+
add_index :comments, :post_id
|
1234
|
+
end
|
1235
|
+
end
|
1236
|
+
</pre>
|
1237
|
+
</div>
|
1238
|
+
<p>The <tt>t.references</tt> line sets up a foreign key column for the association between
|
1239
|
+
the two models. And the <tt>add_index</tt> line sets up an index for this association
|
1240
|
+
column. Go ahead and run the migration:</p>
|
1241
|
+
<div class="code_container">
|
1242
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
1243
|
+
$ rake db:migrate
|
1244
|
+
</pre>
|
1245
|
+
</div>
|
1246
|
+
<p>Rails is smart enough to only execute the migrations that have not already been
|
1247
|
+
run against the current database, so in this case you will just see:</p>
|
1248
|
+
<div class="code_container">
|
1249
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
1250
|
+
== CreateComments: migrating =================================================
|
1251
|
+
-- create_table(:comments)
|
1252
|
+
-> 0.0017s
|
1253
|
+
== CreateComments: migrated (0.0018s) ========================================
|
1254
|
+
</pre>
|
1255
|
+
</div>
|
1256
|
+
<h4 id="associating-models">7.2 Associating Models</h4>
|
1257
|
+
<p>Active Record associations let you easily declare the relationship between two
|
1258
|
+
models. In the case of comments and posts, you could write out the relationships
|
1259
|
+
this way:</p>
|
1260
|
+
<ul>
|
1261
|
+
<li>Each comment belongs to one post.</li>
|
1262
|
+
<li>One post can have many comments.</li>
|
1263
|
+
</ul>
|
1264
|
+
<p>In fact, this is very close to the syntax that Rails uses to declare this
|
1265
|
+
association. You’ve already seen the line of code inside the Comment model that
|
1266
|
+
makes each comment belong to a Post:</p>
|
1267
|
+
<div class="code_container">
|
1268
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1269
|
+
class Comment < ActiveRecord::Base
|
1270
|
+
belongs_to :post
|
1271
|
+
end
|
1272
|
+
</pre>
|
1273
|
+
</div>
|
1274
|
+
<p>You’ll need to edit the <tt>post.rb</tt> file to add the other side of the association:</p>
|
1275
|
+
<div class="code_container">
|
1276
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1277
|
+
class Post < ActiveRecord::Base
|
1278
|
+
validates :name, :presence => true
|
1279
|
+
validates :title, :presence => true,
|
1280
|
+
:length => { :minimum => 5 }
|
1281
|
+
|
1282
|
+
has_many :comments
|
1283
|
+
end
|
1284
|
+
</pre>
|
1285
|
+
</div>
|
1286
|
+
<p>These two declarations enable a good bit of automatic behavior. For example, if
|
1287
|
+
you have an instance variable <tt>@post</tt> containing a post, you can retrieve all
|
1288
|
+
the comments belonging to that post as an array using <tt>@post.comments</tt>.</p>
|
1289
|
+
<div class="info"><p>For more information on Active Record associations, see the <a href="association_basics.html">Active Record
|
1290
|
+
Associations</a> guide.</p></div>
|
1291
|
+
<h4 id="adding-a-route-for-comments">7.3 Adding a Route for Comments</h4>
|
1292
|
+
<p>As with the <tt>home</tt> controller, we will need to add a route so that Rails knows
|
1293
|
+
where we would like to navigate to see <tt>comments</tt>. Open up the
|
1294
|
+
<tt>config/routes.rb</tt> file again. Near the top, you will see the entry for <tt>posts</tt>
|
1295
|
+
that was added automatically by the scaffold generator: <tt>resources
|
1296
|
+
:posts</tt>. Edit it as follows:</p>
|
1297
|
+
<div class="code_container">
|
1298
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1299
|
+
resources :posts do
|
1300
|
+
resources :comments
|
1301
|
+
end
|
1302
|
+
</pre>
|
1303
|
+
</div>
|
1304
|
+
<p>This creates <tt>comments</tt> as a <em>nested resource</em> within <tt>posts</tt>. This is another
|
1305
|
+
part of capturing the hierarchical relationship that exists between posts and
|
1306
|
+
comments.</p>
|
1307
|
+
<div class="info"><p>For more information on routing, see the <a href="routing.html">Rails Routing from the Outside
|
1308
|
+
In</a> guide.</p></div>
|
1309
|
+
<h4 id="generating-a-controller">7.4 Generating a Controller</h4>
|
1310
|
+
<p>With the model in hand, you can turn your attention to creating a matching
|
1311
|
+
controller. Again, there’s a generator for this:</p>
|
1312
|
+
<div class="code_container">
|
1313
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
1314
|
+
$ rails generate controller Comments
|
1315
|
+
</pre>
|
1316
|
+
</div>
|
1317
|
+
<p>This creates six files and one empty directory:</p>
|
1318
|
+
<ul>
|
1319
|
+
<li><tt>app/controllers/comments_controller.rb</tt> – The controller.</li>
|
1320
|
+
<li><tt>app/helpers/comments_helper.rb</tt> – A view helper file.</li>
|
1321
|
+
<li><tt>test/functional/comments_controller_test.rb</tt> – The functional tests for the controller.</li>
|
1322
|
+
<li><tt>test/unit/helpers/comments_helper_test.rb</tt> – The unit tests for the helper.</li>
|
1323
|
+
<li><tt>app/views/comments/</tt> – Views of the controller are stored here.</li>
|
1324
|
+
<li><tt>app/assets/stylesheets/comment.css.scss</tt> – Cascading style sheet for the controller.</li>
|
1325
|
+
<li><tt>app/assets/javascripts/comment.js.coffee</tt> – CoffeeScript for the controller.</li>
|
1326
|
+
</ul>
|
1327
|
+
<p>Like with any blog, our readers will create their comments directly after
|
1328
|
+
reading the post, and once they have added their comment, will be sent back to
|
1329
|
+
the post show page to see their comment now listed. Due to this, our
|
1330
|
+
<tt>CommentsController</tt> is there to provide a method to create comments and delete
|
1331
|
+
spam comments when they arrive.</p>
|
1332
|
+
<p>So first, we’ll wire up the Post show template
|
1333
|
+
(<tt>/app/views/posts/show.html.erb</tt>) to let us make a new comment:</p>
|
1334
|
+
<div class="code_container">
|
1335
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1336
|
+
<p class="notice"><%= notice %></p>
|
1337
|
+
|
1338
|
+
<p>
|
1339
|
+
<b>Name:</b>
|
1340
|
+
<%= @post.name %>
|
1341
|
+
</p>
|
1342
|
+
|
1343
|
+
<p>
|
1344
|
+
<b>Title:</b>
|
1345
|
+
<%= @post.title %>
|
1346
|
+
</p>
|
1347
|
+
|
1348
|
+
<p>
|
1349
|
+
<b>Content:</b>
|
1350
|
+
<%= @post.content %>
|
1351
|
+
</p>
|
1352
|
+
|
1353
|
+
<h2>Add a comment:</h2>
|
1354
|
+
<%= form_for([@post, @post.comments.build]) do |f| %>
|
1355
|
+
<div class="field">
|
1356
|
+
<%= f.label :commenter %><br />
|
1357
|
+
<%= f.text_field :commenter %>
|
1358
|
+
</div>
|
1359
|
+
<div class="field">
|
1360
|
+
<%= f.label :body %><br />
|
1361
|
+
<%= f.text_area :body %>
|
1362
|
+
</div>
|
1363
|
+
<div class="actions">
|
1364
|
+
<%= f.submit %>
|
1365
|
+
</div>
|
1366
|
+
<% end %>
|
1367
|
+
|
1368
|
+
<%= link_to 'Edit Post', edit_post_path(@post) %> |
|
1369
|
+
<%= link_to 'Back to Posts', posts_path %> |
|
1370
|
+
</pre>
|
1371
|
+
</div>
|
1372
|
+
<p>This adds a form on the <tt>Post</tt> show page that creates a new comment by
|
1373
|
+
calling the <tt>CommentsController</tt> <tt>create</tt> action. Let’s wire that up:</p>
|
1374
|
+
<div class="code_container">
|
1375
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1376
|
+
class CommentsController < ApplicationController
|
1377
|
+
def create
|
1378
|
+
@post = Post.find(params[:post_id])
|
1379
|
+
@comment = @post.comments.create(params[:comment])
|
1380
|
+
redirect_to post_path(@post)
|
1381
|
+
end
|
1382
|
+
end
|
1383
|
+
</pre>
|
1384
|
+
</div>
|
1385
|
+
<p>You’ll see a bit more complexity here than you did in the controller for posts.
|
1386
|
+
That’s a side-effect of the nesting that you’ve set up. Each request for a
|
1387
|
+
comment has to keep track of the post to which the comment is attached, thus the
|
1388
|
+
initial call to the <tt>find</tt> method of the <tt>Post</tt> model to get the post in question.</p>
|
1389
|
+
<p>In addition, the code takes advantage of some of the methods available for an
|
1390
|
+
association. We use the <tt>create</tt> method on <tt>@post.comments</tt> to create and save
|
1391
|
+
the comment. This will automatically link the comment so that it belongs to that
|
1392
|
+
particular post.</p>
|
1393
|
+
<p>Once we have made the new comment, we send the user back to the original post
|
1394
|
+
using the <tt>post_path(@post)</tt> helper. As we have already seen, this calls the
|
1395
|
+
<tt>show</tt> action of the <tt>PostsController</tt> which in turn renders the <tt>show.html.erb</tt>
|
1396
|
+
template. This is where we want the comment to show, so let’s add that to the
|
1397
|
+
<tt>app/views/posts/show.html.erb</tt>.</p>
|
1398
|
+
<div class="code_container">
|
1399
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1400
|
+
<p class="notice"><%= notice %></p>
|
1401
|
+
|
1402
|
+
<p>
|
1403
|
+
<b>Name:</b>
|
1404
|
+
<%= @post.name %>
|
1405
|
+
</p>
|
1406
|
+
|
1407
|
+
<p>
|
1408
|
+
<b>Title:</b>
|
1409
|
+
<%= @post.title %>
|
1410
|
+
</p>
|
1411
|
+
|
1412
|
+
<p>
|
1413
|
+
<b>Content:</b>
|
1414
|
+
<%= @post.content %>
|
1415
|
+
</p>
|
1416
|
+
|
1417
|
+
<h2>Comments</h2>
|
1418
|
+
<% @post.comments.each do |comment| %>
|
1419
|
+
<p>
|
1420
|
+
<b>Commenter:</b>
|
1421
|
+
<%= comment.commenter %>
|
1422
|
+
</p>
|
1423
|
+
|
1424
|
+
<p>
|
1425
|
+
<b>Comment:</b>
|
1426
|
+
<%= comment.body %>
|
1427
|
+
</p>
|
1428
|
+
<% end %>
|
1429
|
+
|
1430
|
+
<h2>Add a comment:</h2>
|
1431
|
+
<%= form_for([@post, @post.comments.build]) do |f| %>
|
1432
|
+
<div class="field">
|
1433
|
+
<%= f.label :commenter %><br />
|
1434
|
+
<%= f.text_field :commenter %>
|
1435
|
+
</div>
|
1436
|
+
<div class="field">
|
1437
|
+
<%= f.label :body %><br />
|
1438
|
+
<%= f.text_area :body %>
|
1439
|
+
</div>
|
1440
|
+
<div class="actions">
|
1441
|
+
<%= f.submit %>
|
1442
|
+
</div>
|
1443
|
+
<% end %>
|
1444
|
+
|
1445
|
+
<br />
|
1446
|
+
|
1447
|
+
<%= link_to 'Edit Post', edit_post_path(@post) %> |
|
1448
|
+
<%= link_to 'Back to Posts', posts_path %> |
|
1449
|
+
</pre>
|
1450
|
+
</div>
|
1451
|
+
<p>Now you can add posts and comments to your blog and have them show up in the
|
1452
|
+
right places.</p>
|
1453
|
+
<h3 id="refactoring">8 Refactoring</h3>
|
1454
|
+
<p>Now that we have posts and comments working, take a look at the
|
1455
|
+
<tt>app/views/posts/show.html.erb</tt> template. It is getting long and awkward. We can
|
1456
|
+
use partials to clean it up.</p>
|
1457
|
+
<h4 id="rendering-partial-collections">8.1 Rendering Partial Collections</h4>
|
1458
|
+
<p>First we will make a comment partial to extract showing all the comments for the
|
1459
|
+
post. Create the file <tt>app/views/comments/_comment.html.erb</tt> and put the
|
1460
|
+
following into it:</p>
|
1461
|
+
<div class="code_container">
|
1462
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1463
|
+
<p>
|
1464
|
+
<b>Commenter:</b>
|
1465
|
+
<%= comment.commenter %>
|
1466
|
+
</p>
|
1467
|
+
|
1468
|
+
<p>
|
1469
|
+
<b>Comment:</b>
|
1470
|
+
<%= comment.body %>
|
1471
|
+
</p>
|
1472
|
+
</pre>
|
1473
|
+
</div>
|
1474
|
+
<p>Then you can change <tt>app/views/posts/show.html.erb</tt> to look like the
|
1475
|
+
following:</p>
|
1476
|
+
<div class="code_container">
|
1477
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1478
|
+
<p class="notice"><%= notice %></p>
|
1479
|
+
|
1480
|
+
<p>
|
1481
|
+
<b>Name:</b>
|
1482
|
+
<%= @post.name %>
|
1483
|
+
</p>
|
1484
|
+
|
1485
|
+
<p>
|
1486
|
+
<b>Title:</b>
|
1487
|
+
<%= @post.title %>
|
1488
|
+
</p>
|
1489
|
+
|
1490
|
+
<p>
|
1491
|
+
<b>Content:</b>
|
1492
|
+
<%= @post.content %>
|
1493
|
+
</p>
|
1494
|
+
|
1495
|
+
<h2>Comments</h2>
|
1496
|
+
<%= render @post.comments %>
|
1497
|
+
|
1498
|
+
<h2>Add a comment:</h2>
|
1499
|
+
<%= form_for([@post, @post.comments.build]) do |f| %>
|
1500
|
+
<div class="field">
|
1501
|
+
<%= f.label :commenter %><br />
|
1502
|
+
<%= f.text_field :commenter %>
|
1503
|
+
</div>
|
1504
|
+
<div class="field">
|
1505
|
+
<%= f.label :body %><br />
|
1506
|
+
<%= f.text_area :body %>
|
1507
|
+
</div>
|
1508
|
+
<div class="actions">
|
1509
|
+
<%= f.submit %>
|
1510
|
+
</div>
|
1511
|
+
<% end %>
|
1512
|
+
|
1513
|
+
<br />
|
1514
|
+
|
1515
|
+
<%= link_to 'Edit Post', edit_post_path(@post) %> |
|
1516
|
+
<%= link_to 'Back to Posts', posts_path %> |
|
1517
|
+
</pre>
|
1518
|
+
</div>
|
1519
|
+
<p>This will now render the partial in <tt>app/views/comments/_comment.html.erb</tt> once
|
1520
|
+
for each comment that is in the <tt>@post.comments</tt> collection. As the <tt>render</tt>
|
1521
|
+
method iterates over the <tt>@post.comments</tt> collection, it assigns each
|
1522
|
+
comment to a local variable named the same as the partial, in this case
|
1523
|
+
<tt>comment</tt> which is then available in the partial for us to show.</p>
|
1524
|
+
<h4 id="rendering-a-partial-form">8.2 Rendering a Partial Form</h4>
|
1525
|
+
<p>Let us also move that new comment section out to its own partial. Again, you
|
1526
|
+
create a file <tt>app/views/comments/_form.html.erb</tt> containing:</p>
|
1527
|
+
<div class="code_container">
|
1528
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1529
|
+
<%= form_for([@post, @post.comments.build]) do |f| %>
|
1530
|
+
<div class="field">
|
1531
|
+
<%= f.label :commenter %><br />
|
1532
|
+
<%= f.text_field :commenter %>
|
1533
|
+
</div>
|
1534
|
+
<div class="field">
|
1535
|
+
<%= f.label :body %><br />
|
1536
|
+
<%= f.text_area :body %>
|
1537
|
+
</div>
|
1538
|
+
<div class="actions">
|
1539
|
+
<%= f.submit %>
|
1540
|
+
</div>
|
1541
|
+
<% end %>
|
1542
|
+
</pre>
|
1543
|
+
</div>
|
1544
|
+
<p>Then you make the <tt>app/views/posts/show.html.erb</tt> look like the following:</p>
|
1545
|
+
<div class="code_container">
|
1546
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1547
|
+
<p class="notice"><%= notice %></p>
|
1548
|
+
|
1549
|
+
<p>
|
1550
|
+
<b>Name:</b>
|
1551
|
+
<%= @post.name %>
|
1552
|
+
</p>
|
1553
|
+
|
1554
|
+
<p>
|
1555
|
+
<b>Title:</b>
|
1556
|
+
<%= @post.title %>
|
1557
|
+
</p>
|
1558
|
+
|
1559
|
+
<p>
|
1560
|
+
<b>Content:</b>
|
1561
|
+
<%= @post.content %>
|
1562
|
+
</p>
|
1563
|
+
|
1564
|
+
<h2>Comments</h2>
|
1565
|
+
<%= render @post.comments %>
|
1566
|
+
|
1567
|
+
<h2>Add a comment:</h2>
|
1568
|
+
<%= render "comments/form" %>
|
1569
|
+
|
1570
|
+
<br />
|
1571
|
+
|
1572
|
+
<%= link_to 'Edit Post', edit_post_path(@post) %> |
|
1573
|
+
<%= link_to 'Back to Posts', posts_path %> |
|
1574
|
+
</pre>
|
1575
|
+
</div>
|
1576
|
+
<p>The second render just defines the partial template we want to render,
|
1577
|
+
<tt>comments/form</tt>. Rails is smart enough to spot the forward slash in that
|
1578
|
+
string and realize that you want to render the <tt>_form.html.erb</tt> file in
|
1579
|
+
the <tt>app/views/comments</tt> directory.</p>
|
1580
|
+
<p>The <tt>@post</tt> object is available to any partials rendered in the view because we
|
1581
|
+
defined it as an instance variable.</p>
|
1582
|
+
<h3 id="deleting-comments">9 Deleting Comments</h3>
|
1583
|
+
<p>Another important feature of a blog is being able to delete spam comments. To do
|
1584
|
+
this, we need to implement a link of some sort in the view and a <tt>DELETE</tt> action
|
1585
|
+
in the <tt>CommentsController</tt>.</p>
|
1586
|
+
<p>So first, let’s add the delete link in the
|
1587
|
+
<tt>app/views/comments/_comment.html.erb</tt> partial:</p>
|
1588
|
+
<div class="code_container">
|
1589
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1590
|
+
<p>
|
1591
|
+
<b>Commenter:</b>
|
1592
|
+
<%= comment.commenter %>
|
1593
|
+
</p>
|
1594
|
+
|
1595
|
+
<p>
|
1596
|
+
<b>Comment:</b>
|
1597
|
+
<%= comment.body %>
|
1598
|
+
</p>
|
1599
|
+
|
1600
|
+
<p>
|
1601
|
+
<%= link_to 'Destroy Comment', [comment.post, comment],
|
1602
|
+
:confirm => 'Are you sure?',
|
1603
|
+
:method => :delete %>
|
1604
|
+
</p>
|
1605
|
+
</pre>
|
1606
|
+
</div>
|
1607
|
+
<p>Clicking this new “Destroy Comment” link will fire off a <tt><span class="caps">DELETE</span>
|
1608
|
+
/posts/:id/comments/:id</tt> to our <tt>CommentsController</tt>, which can then use
|
1609
|
+
this to find the comment we want to delete, so let’s add a destroy action to our
|
1610
|
+
controller:</p>
|
1611
|
+
<div class="code_container">
|
1612
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1613
|
+
class CommentsController < ApplicationController
|
1614
|
+
|
1615
|
+
def create
|
1616
|
+
@post = Post.find(params[:post_id])
|
1617
|
+
@comment = @post.comments.create(params[:comment])
|
1618
|
+
redirect_to post_path(@post)
|
1619
|
+
end
|
1620
|
+
|
1621
|
+
def destroy
|
1622
|
+
@post = Post.find(params[:post_id])
|
1623
|
+
@comment = @post.comments.find(params[:id])
|
1624
|
+
@comment.destroy
|
1625
|
+
redirect_to post_path(@post)
|
1626
|
+
end
|
1627
|
+
|
1628
|
+
end
|
1629
|
+
</pre>
|
1630
|
+
</div>
|
1631
|
+
<p>The <tt>destroy</tt> action will find the post we are looking at, locate the comment
|
1632
|
+
within the <tt>@post.comments</tt> collection, and then remove it from the
|
1633
|
+
database and send us back to the show action for the post.</p>
|
1634
|
+
<h4 id="deleting-associated-objects">9.1 Deleting Associated Objects</h4>
|
1635
|
+
<p>If you delete a post then its associated comments will also need to be deleted.
|
1636
|
+
Otherwise they would simply occupy space in the database. Rails allows you to
|
1637
|
+
use the <tt>dependent</tt> option of an association to achieve this. Modify the Post
|
1638
|
+
model, <tt>app/models/post.rb</tt>, as follows:</p>
|
1639
|
+
<div class="code_container">
|
1640
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1641
|
+
class Post < ActiveRecord::Base
|
1642
|
+
validates :name, :presence => true
|
1643
|
+
validates :title, :presence => true,
|
1644
|
+
:length => { :minimum => 5 }
|
1645
|
+
has_many :comments, :dependent => :destroy
|
1646
|
+
end
|
1647
|
+
</pre>
|
1648
|
+
</div>
|
1649
|
+
<h3 id="security">10 Security</h3>
|
1650
|
+
<p>If you were to publish your blog online, anybody would be able to add, edit and
|
1651
|
+
delete posts or delete comments.</p>
|
1652
|
+
<p>Rails provides a very simple <span class="caps">HTTP</span> authentication system that will work nicely in
|
1653
|
+
this situation.</p>
|
1654
|
+
<p>In the <tt>PostsController</tt> we need to have a way to block access to the various
|
1655
|
+
actions if the person is not authenticated, here we can use the Rails
|
1656
|
+
<tt>http_basic_authenticate_with</tt> method, allowing access to the requested
|
1657
|
+
action if that method allows it.</p>
|
1658
|
+
<p>To use the authentication system, we specify it at the top of our
|
1659
|
+
<tt>PostsController</tt>, in this case, we want the user to be authenticated on every
|
1660
|
+
action, except for <tt>index</tt> and <tt>show</tt>, so we write that:</p>
|
1661
|
+
<div class="code_container">
|
1662
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1663
|
+
class PostsController < ApplicationController
|
1664
|
+
|
1665
|
+
http_basic_authenticate_with :name => "dhh", :password => "secret", :except => [:index, :show]
|
1666
|
+
|
1667
|
+
# GET /posts
|
1668
|
+
# GET /posts.json
|
1669
|
+
def index
|
1670
|
+
@posts = Post.all
|
1671
|
+
respond_to do |format|
|
1672
|
+
# snipped for brevity
|
1673
|
+
</pre>
|
1674
|
+
</div>
|
1675
|
+
<p>We also only want to allow authenticated users to delete comments, so in the
|
1676
|
+
<tt>CommentsController</tt> we write:</p>
|
1677
|
+
<div class="code_container">
|
1678
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1679
|
+
class CommentsController < ApplicationController
|
1680
|
+
|
1681
|
+
http_basic_authenticate_with :name => "dhh", :password => "secret", :only => :destroy
|
1682
|
+
|
1683
|
+
def create
|
1684
|
+
@post = Post.find(params[:post_id])
|
1685
|
+
# snipped for brevity
|
1686
|
+
</pre>
|
1687
|
+
</div>
|
1688
|
+
<p>Now if you try to create a new post, you will be greeted with a basic <span class="caps">HTTP</span>
|
1689
|
+
Authentication challenge</p>
|
1690
|
+
<p><img src="images/challenge.png" title="Basic HTTP Authentication Challenge" alt="Basic HTTP Authentication Challenge" /></p>
|
1691
|
+
<h3 id="building-a-multi-model-form">11 Building a Multi-Model Form</h3>
|
1692
|
+
<p>Another feature of your average blog is the ability to tag posts. To implement
|
1693
|
+
this feature your application needs to interact with more than one model on a
|
1694
|
+
single form. Rails offers support for nested forms.</p>
|
1695
|
+
<p>To demonstrate this, we will add support for giving each post multiple tags,
|
1696
|
+
right in the form where you create the post. First, create a new model to hold
|
1697
|
+
the tags:</p>
|
1698
|
+
<div class="code_container">
|
1699
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
1700
|
+
$ rails generate model tag name:string post:references
|
1701
|
+
</pre>
|
1702
|
+
</div>
|
1703
|
+
<p>Again, run the migration to create the database table:</p>
|
1704
|
+
<div class="code_container">
|
1705
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
1706
|
+
$ rake db:migrate
|
1707
|
+
</pre>
|
1708
|
+
</div>
|
1709
|
+
<p>Next, edit the <tt>post.rb</tt> file to create the other side of the association, and
|
1710
|
+
to tell Rails (via the <tt>accepts_nested_attributes_for</tt> macro) that you intend to
|
1711
|
+
edit tags via posts:</p>
|
1712
|
+
<div class="code_container">
|
1713
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
1714
|
+
class Post < ActiveRecord::Base
|
1715
|
+
validates :name, :presence => true
|
1716
|
+
validates :title, :presence => true,
|
1717
|
+
:length => { :minimum => 5 }
|
1718
|
+
|
1719
|
+
has_many :comments, :dependent => :destroy
|
1720
|
+
has_many :tags
|
1721
|
+
|
1722
|
+
accepts_nested_attributes_for :tags, :allow_destroy => :true,
|
1723
|
+
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
|
1724
|
+
end
|
1725
|
+
</pre>
|
1726
|
+
</div>
|
1727
|
+
<p>The <tt>:allow_destroy</tt> option on the nested attribute declaration tells Rails to
|
1728
|
+
display a “remove” checkbox on the view that you’ll build shortly. The
|
1729
|
+
<tt>:reject_if</tt> option prevents saving new tags that do not have any attributes
|
1730
|
+
filled in.</p>
|
1731
|
+
<p>We will modify <tt>views/posts/_form.html.erb</tt> to render a partial to make a tag:</p>
|
1732
|
+
<div class="code_container">
|
1733
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1734
|
+
<% @post.tags.build %>
|
1735
|
+
<%= form_for(@post) do |post_form| %>
|
1736
|
+
<% if @post.errors.any? %>
|
1737
|
+
<div id="errorExplanation">
|
1738
|
+
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
|
1739
|
+
<ul>
|
1740
|
+
<% @post.errors.full_messages.each do |msg| %>
|
1741
|
+
<li><%= msg %></li>
|
1742
|
+
<% end %>
|
1743
|
+
</ul>
|
1744
|
+
</div>
|
1745
|
+
<% end %>
|
1746
|
+
|
1747
|
+
<div class="field">
|
1748
|
+
<%= post_form.label :name %><br />
|
1749
|
+
<%= post_form.text_field :name %>
|
1750
|
+
</div>
|
1751
|
+
<div class="field">
|
1752
|
+
<%= post_form.label :title %><br />
|
1753
|
+
<%= post_form.text_field :title %>
|
1754
|
+
</div>
|
1755
|
+
<div class="field">
|
1756
|
+
<%= post_form.label :content %><br />
|
1757
|
+
<%= post_form.text_area :content %>
|
1758
|
+
</div>
|
1759
|
+
<h2>Tags</h2>
|
1760
|
+
<%= render :partial => 'tags/form',
|
1761
|
+
:locals => {:form => post_form} %>
|
1762
|
+
<div class="actions">
|
1763
|
+
<%= post_form.submit %>
|
1764
|
+
</div>
|
1765
|
+
<% end %>
|
1766
|
+
</pre>
|
1767
|
+
</div>
|
1768
|
+
<p>Note that we have changed the <tt>f</tt> in <tt>form_for(@post) do |f|</tt> to <tt>post_form</tt> to
|
1769
|
+
make it easier to understand what is going on.</p>
|
1770
|
+
<p>This example shows another option of the render helper, being able to pass in
|
1771
|
+
local variables, in this case, we want the local variable <tt>form</tt> in the partial
|
1772
|
+
to refer to the <tt>post_form</tt> object.</p>
|
1773
|
+
<p>We also add a <tt>@post.tags.build</tt> at the top of this form. This is to make
|
1774
|
+
sure there is a new tag ready to have its name filled in by the user. If you do
|
1775
|
+
not build the new tag, then the form will not appear as there is no new Tag
|
1776
|
+
object ready to create.</p>
|
1777
|
+
<p>Now create the folder <tt>app/views/tags</tt> and make a file in there called
|
1778
|
+
<tt>_form.html.erb</tt> which contains the form for the tag:</p>
|
1779
|
+
<div class="code_container">
|
1780
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1781
|
+
<%= form.fields_for :tags do |tag_form| %>
|
1782
|
+
<div class="field">
|
1783
|
+
<%= tag_form.label :name, 'Tag:' %>
|
1784
|
+
<%= tag_form.text_field :name %>
|
1785
|
+
</div>
|
1786
|
+
<% unless tag_form.object.nil? || tag_form.object.new_record? %>
|
1787
|
+
<div class="field">
|
1788
|
+
<%= tag_form.label :_destroy, 'Remove:' %>
|
1789
|
+
<%= tag_form.check_box :_destroy %>
|
1790
|
+
</div>
|
1791
|
+
<% end %>
|
1792
|
+
<% end %>
|
1793
|
+
</pre>
|
1794
|
+
</div>
|
1795
|
+
<p>Finally, we will edit the <tt>app/views/posts/show.html.erb</tt> template to
|
1796
|
+
show our tags.</p>
|
1797
|
+
<div class="code_container">
|
1798
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1799
|
+
<p class="notice"><%= notice %></p>
|
1800
|
+
|
1801
|
+
<p>
|
1802
|
+
<b>Name:</b>
|
1803
|
+
<%= @post.name %>
|
1804
|
+
</p>
|
1805
|
+
|
1806
|
+
<p>
|
1807
|
+
<b>Title:</b>
|
1808
|
+
<%= @post.title %>
|
1809
|
+
</p>
|
1810
|
+
|
1811
|
+
<p>
|
1812
|
+
<b>Content:</b>
|
1813
|
+
<%= @post.content %>
|
1814
|
+
</p>
|
1815
|
+
|
1816
|
+
<p>
|
1817
|
+
<b>Tags:</b>
|
1818
|
+
<%= @post.tags.map { |t| t.name }.join(", ") %>
|
1819
|
+
</p>
|
1820
|
+
|
1821
|
+
<h2>Comments</h2>
|
1822
|
+
<%= render @post.comments %>
|
1823
|
+
|
1824
|
+
<h2>Add a comment:</h2>
|
1825
|
+
<%= render "comments/form" %>
|
1826
|
+
|
1827
|
+
|
1828
|
+
<%= link_to 'Edit Post', edit_post_path(@post) %> |
|
1829
|
+
<%= link_to 'Back to Posts', posts_path %> |
|
1830
|
+
</pre>
|
1831
|
+
</div>
|
1832
|
+
<p>With these changes in place, you’ll find that you can edit a post and its tags
|
1833
|
+
directly on the same view.</p>
|
1834
|
+
<p>However, that method call <tt>@post.tags.map { |t| t.name }.join(", ")</tt> is
|
1835
|
+
awkward, we could handle this by making a helper method.</p>
|
1836
|
+
<h3 id="view-helpers">12 View Helpers</h3>
|
1837
|
+
<p>View Helpers live in <tt>app/helpers</tt> and provide small snippets of reusable
|
1838
|
+
code for views. In our case, we want a method that strings a bunch of objects
|
1839
|
+
together using their name attribute and joining them with a comma. As this is
|
1840
|
+
for the Post show template, we put it in the PostsHelper.</p>
|
1841
|
+
<p>Open up <tt>app/helpers/posts_helper.rb</tt> and add the following:</p>
|
1842
|
+
<div class="code_container">
|
1843
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1844
|
+
module PostsHelper
|
1845
|
+
def join_tags(post)
|
1846
|
+
post.tags.map { |t| t.name }.join(", ")
|
1847
|
+
end
|
1848
|
+
end
|
1849
|
+
</pre>
|
1850
|
+
</div>
|
1851
|
+
<p>Now you can edit the view in <tt>app/views/posts/show.html.erb</tt> to look like
|
1852
|
+
this:</p>
|
1853
|
+
<div class="code_container">
|
1854
|
+
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
1855
|
+
<p class="notice"><%= notice %></p>
|
1856
|
+
|
1857
|
+
<p>
|
1858
|
+
<b>Name:</b>
|
1859
|
+
<%= @post.name %>
|
1860
|
+
</p>
|
1861
|
+
|
1862
|
+
<p>
|
1863
|
+
<b>Title:</b>
|
1864
|
+
<%= @post.title %>
|
1865
|
+
</p>
|
1866
|
+
|
1867
|
+
<p>
|
1868
|
+
<b>Content:</b>
|
1869
|
+
<%= @post.content %>
|
1870
|
+
</p>
|
1871
|
+
|
1872
|
+
<p>
|
1873
|
+
<b>Tags:</b>
|
1874
|
+
<%= join_tags(@post) %>
|
1875
|
+
</p>
|
1876
|
+
|
1877
|
+
<h2>Comments</h2>
|
1878
|
+
<%= render @post.comments %>
|
1879
|
+
|
1880
|
+
<h2>Add a comment:</h2>
|
1881
|
+
<%= render "comments/form" %>
|
1882
|
+
|
1883
|
+
|
1884
|
+
<%= link_to 'Edit Post', edit_post_path(@post) %> |
|
1885
|
+
<%= link_to 'Back to Posts', posts_path %> |
|
1886
|
+
</pre>
|
1887
|
+
</div>
|
1888
|
+
<h3 id="what-s-next">13 What’s Next?</h3>
|
1889
|
+
<p>Now that you’ve seen your first Rails application, you should feel free to
|
1890
|
+
update it and experiment on your own. But you don’t have to do everything
|
1891
|
+
without help. As you need assistance getting up and running with Rails, feel
|
1892
|
+
free to consult these support resources:</p>
|
1893
|
+
<ul>
|
1894
|
+
<li>The <a href="index.html">Ruby on Rails guides</a></li>
|
1895
|
+
<li>The <a href="http://railstutorial.org/book">Ruby on Rails Tutorial</a></li>
|
1896
|
+
<li>The <a href="http://groups.google.com/group/rubyonrails-talk">Ruby on Rails mailing list</a></li>
|
1897
|
+
<li>The <a href="irc://irc.freenode.net/#rubyonrails">#rubyonrails</a> channel on irc.freenode.net</li>
|
1898
|
+
<li>The <a href="http://wiki.rubyonrails.org/">Rails Wiki</a></li>
|
1899
|
+
</ul>
|
1900
|
+
<p>Rails also comes with built-in help that you can generate using the rake command-line utility:</p>
|
1901
|
+
<ul>
|
1902
|
+
<li>Running <tt>rake doc:guides</tt> will put a full copy of the Rails Guides in the <tt>doc/guides</tt> folder of your application. Open <tt>doc/guides/index.html</tt> in your web browser to explore the Guides.</li>
|
1903
|
+
<li>Running <tt>rake doc:rails</tt> will put a full copy of the <span class="caps">API</span> documentation for Rails in the <tt>doc/api</tt> folder of your application. Open <tt>doc/api/index.html</tt> in your web browser to explore the <span class="caps">API</span> documentation.</li>
|
1904
|
+
</ul>
|
1905
|
+
<h3 id="configuration-gotchas">14 Configuration Gotchas</h3>
|
1906
|
+
<p>The easiest way to work with Rails is to store all external data as <span class="caps">UTF</span>-8. If
|
1907
|
+
you don’t, Ruby libraries and Rails will often be able to convert your native
|
1908
|
+
data into <span class="caps">UTF</span>-8, but this doesn’t always work reliably, so you’re better off
|
1909
|
+
ensuring that all external data is <span class="caps">UTF</span>-8.</p>
|
1910
|
+
<p>If you have made a mistake in this area, the most common symptom is a black
|
1911
|
+
diamond with a question mark inside appearing in the browser. Another common
|
1912
|
+
symptom is characters like “ü” appearing instead of “ü”. Rails takes a number
|
1913
|
+
of internal steps to mitigate common causes of these problems that can be
|
1914
|
+
automatically detected and corrected. However, if you have external data that is
|
1915
|
+
not stored as <span class="caps">UTF</span>-8, it can occasionally result in these kinds of issues that
|
1916
|
+
cannot be automatically detected by Rails and corrected.</p>
|
1917
|
+
<p>Two very common sources of data that are not <span class="caps">UTF</span>-8:</p>
|
1918
|
+
<ul>
|
1919
|
+
<li>Your text editor: Most text editors (such as Textmate), default to saving files as
|
1920
|
+
<span class="caps">UTF</span>-8. If your text editor does not, this can result in special characters that you
|
1921
|
+
enter in your templates (such as é) to appear as a diamond with a question mark inside
|
1922
|
+
in the browser. This also applies to your I18N translation files.
|
1923
|
+
Most editors that do not already default to <span class="caps">UTF</span>-8 (such as some versions of
|
1924
|
+
Dreamweaver) offer a way to change the default to <span class="caps">UTF</span>-8. Do so.</li>
|
1925
|
+
<li>Your database. Rails defaults to converting data from your database into <span class="caps">UTF</span>-8 at
|
1926
|
+
the boundary. However, if your database is not using <span class="caps">UTF</span>-8 internally, it may not
|
1927
|
+
be able to store all characters that your users enter. For instance, if your database
|
1928
|
+
is using Latin-1 internally, and your user enters a Russian, Hebrew, or Japanese
|
1929
|
+
character, the data will be lost forever once it enters the database. If possible,
|
1930
|
+
use <span class="caps">UTF</span>-8 as the internal storage of your database.</li>
|
1931
|
+
</ul>
|
1932
|
+
|
1933
|
+
<h3>Feedback</h3>
|
1934
|
+
<p>
|
1935
|
+
You're encouraged to help improve the quality of this guide.
|
1936
|
+
</p>
|
1937
|
+
<p>
|
1938
|
+
If you see any typos or factual errors you are confident to
|
1939
|
+
patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
|
1940
|
+
and push the change yourself. That branch of Rails has public write access.
|
1941
|
+
Commits are still reviewed, but that happens after you've submitted your
|
1942
|
+
contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
|
1943
|
+
cross-merged with master periodically.
|
1944
|
+
</p>
|
1945
|
+
<p>
|
1946
|
+
You may also find incomplete content, or stuff that is not up to date.
|
1947
|
+
Please do add any missing documentation for master. Check the
|
1948
|
+
<a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
|
1949
|
+
for style and conventions.
|
1950
|
+
</p>
|
1951
|
+
<p>
|
1952
|
+
If for whatever reason you spot something to fix but cannot patch it yourself, please
|
1953
|
+
<a href="https://github.com/rails/rails/issues">open an issue</a>.
|
1954
|
+
</p>
|
1955
|
+
<p>And last but not least, any kind of discussion regarding Ruby on Rails
|
1956
|
+
documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
|
1957
|
+
</p>
|
1958
|
+
</div>
|
1959
|
+
</div>
|
1960
|
+
</div>
|
1961
|
+
|
1962
|
+
<hr class="hide" />
|
1963
|
+
<div id="footer">
|
1964
|
+
<div class="wrapper">
|
1965
|
+
<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
|
1966
|
+
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
|
1967
|
+
</div>
|
1968
|
+
</div>
|
1969
|
+
|
1970
|
+
<script type="text/javascript" src="javascripts/guides.js"></script>
|
1971
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
|
1972
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
|
1973
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
|
1974
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
|
1975
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
|
1976
|
+
<script type="text/javascript">
|
1977
|
+
SyntaxHighlighter.all()
|
1978
|
+
</script>
|
1979
|
+
</body>
|
1980
|
+
</html>
|