diff options
author | Mike Gunderloy <MikeG1@larkfarm.com> | 2008-10-16 07:01:35 -0500 |
---|---|---|
committer | Mike Gunderloy <MikeG1@larkfarm.com> | 2008-10-16 07:06:36 -0500 |
commit | 7f744244e120ace985c85ec738da337f88f4f6f0 (patch) | |
tree | 464e1c9515270fb56ddbb39327f8ab19da7adae8 /railties/doc/guides/getting_started_with_rails | |
parent | 27ad5c4bbbd98d3ca6cb0877f1b29bd95f6285f1 (diff) | |
download | rails-7f744244e120ace985c85ec738da337f88f4f6f0.tar.gz rails-7f744244e120ace985c85ec738da337f88f4f6f0.tar.bz2 rails-7f744244e120ace985c85ec738da337f88f4f6f0.zip |
Revised draft of Getting Started guide.
Diffstat (limited to 'railties/doc/guides/getting_started_with_rails')
-rw-r--r-- | railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt | 260 |
1 files changed, 223 insertions, 37 deletions
diff --git a/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt b/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt index 88f99e73c7..5cc3db2748 100644 --- a/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt +++ b/railties/doc/guides/getting_started_with_rails/getting_started_with_rails.txt @@ -16,7 +16,10 @@ This guide is designed for beginners who want to get started with a Rails applic * The link:http://rubyforge.org/frs/?group_id=126[RubyGems] packaging system * A working installation of link:http://www.sqlite.org/[SQLite] (preferred), link:http://www.mysql.com/[MySQL], or link:http://www.postgresql.org/[PostgreSQL] -It is highly recommended that you *familiarize yourself with Ruby before diving into Rails*. You will find it much easier to follow what's going on with a Rails application if you understand basic Ruby syntax. Rails isn't going to magically revolutionize the way you write web applications if you have no experience with the language it uses. +It is highly recommended that you *familiarize yourself with Ruby before diving into Rails*. You will find it much easier to follow what's going on with a Rails application if you understand basic Ruby syntax. Rails isn't going to magically revolutionize the way you write web applications if you have no experience with the language it uses. There are some good free resources on the net for learning Ruby, including: + +* link:http://www.rubycentral.com/book/[Programming Ruby] +* link:http://poignantguide.net/ruby/[Why's (Poignant) Guide to Ruby] == What is Rails? @@ -30,7 +33,8 @@ The Rails philosophy includes several guiding principles: * Convention Over Configuration - means that Rails makes assumptions about what you want to do and how you're going to do it, rather than letting you tweak every little thing through endless configuration files. * REST is the best pattern for web applications - organizing your application around resources and standard HTTP verbs is the fastest way to go. -=== Models, Views, and Controllers +=== The MVC Architecture + Rails is organized around the Model, View, Controller architecture, usually just called MVC. MVC benefits include: * Isolation of business logic from the user interface @@ -49,9 +53,49 @@ Views represent the user interface of your application. In Rails, views are ofte Controllers provide the "glue" between models and views. In Rails, controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation. +=== The Components of Rails + +Rails provides a full stack of components for creating web applications, including: + +* Action Controller +* Action View +* Active Record +* Action Mailer +* Active Resource +* Railties +* Active Support + +==== Action Controller + +Action Controller is the component that manages the controllers in a Rails application. The Action Controller framework processes incoming requests to a Rails application, extracts parameters, and dispatches them to the intended action. Services provided by Action Controller include session management, template rendering, and redirect management. + +==== Action View + +Action View manages the views of your Rails application. It can create both HTML and XML output by default. Action View manages rendering templates, including nested and partial templates, and includes built-in AJAX support. + +==== Active Record + +Active Record is the base for the models in a Rails application. It provides database independence, basic CRUD functionality, advanced finding capabilities, and the ability to relate models to one another, among other services. + +==== Action Mailer + +Action Mailer is a framework for building e-mail services. You can use Action Mailer to send emails based on flexible templates, or to receive and process incoming email. + +==== Active Resource + +Active Resource provides a framework for managing the connection between business objects an RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics. + +==== Railties + +Railties is the core Rails code that builds new Rails applications and glues the various frameworks together in any Rails application. + +==== Active Support + +Active Support is an extensive collection of utility classes and standard Ruby library extensions that are used in the Rails, both by the core code and by your applications. + === REST -The foundation of RESTful routing is generally considered to be Roy Fielding's doctoral thesis, link:http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm[Architectural Styles and the Design of Network-based Software Architectures]. Fortunately, you need not read this entire document to understand how REST works in Rails. REST, an acronym for Representational State Transfer, boils down to two main principles for our purposes: +The foundation of the RESTful architecture is generally considered to be Roy Fielding's doctoral thesis, link:http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm[Architectural Styles and the Design of Network-based Software Architectures]. Fortunately, you need not read this entire document to understand how REST works in Rails. REST, an acronym for Representational State Transfer, boils down to two main principles for our purposes: * Using resource identifiers (which, for the purposes of discussion, you can think of as URLs) to represent resources * Transferring representations of the state of that resource between system components. @@ -72,7 +116,7 @@ In most cases, the easiest way to install Rails is to take advantage of RubyGems [source, shell] ------------------------------------------------------- -gem install rails +$ gem install rails ------------------------------------------------------- NOTE: There are some special circumstances in which you might want to use an alternate installation strategy: @@ -86,21 +130,21 @@ Open a terminal, navigate to a folder where you have rights to create files, and [source, shell] ------------------------------------------------------- -rails blog +$ rails blog ------------------------------------------------------- This will create a Rails application that uses a SQLite database for data storage. If you prefer to use MySQL, run this command instead: [source, shell] ------------------------------------------------------- -rails blog -d mysql +$ rails blog -d mysql ------------------------------------------------------- And if you're using PostgreSQL for data storage, run this command: [source, shell] ------------------------------------------------------- -rails blog -d postgresql +$ rails blog -d postgresql ------------------------------------------------------- In any case, Rails will create a folder in your working directory called +blog+. Open up that folder and explore its contents. Most of the work in this tutorial will happen in the +app/+ folder, but here's a basic rundown on the function of each folder that Rails creates in a new application by default: @@ -121,20 +165,23 @@ File/Folder Purpose +script/+ Scripts provided by Rails to do recurring tasks, such as benchmarking, plugin installation, and starting the console or the web server. +test/+ Unit tests, fixtures, and other test apparatus. These are covered in link:../testing_rails_applications/testing_rails_applications.html[Testing Rails Applications] +tmp/+ Temporary files -+vendor/+ The Rails source code (if you install it into your project) and plugins containing additional prepackaged functionality. ++vendor/+ A place for 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. ------------------------------------------------------------------------------------------------------------------------------------------- -=== Configuring a SQLite Database - -Rails comes with built-in support for SQLite, which is a lightweight flat-file based database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later. +=== Configuring a Database -If you open the file +config/database.yml+ you'll see a default database configuration using SQLite. The file contains sections for three different environments in which Rails can run by default: +Just about every Rails application will interact with a database. The database to use is specified in a configuration file, +config/database.yml+. +If you open this file in a new Rails application, you'll see a default database configuration using SQLite. The file contains sections for three different environments in which Rails can run by default: * The +development+ environment is used on your development computer as you interact manually with the application * The +test+ environment is used to run automated tests * The +production+ environment is used when you deploy your application for the world to use. -Here's the section of the configuration file with connection information for the development environment: +==== Configuring a SQLite Database + +Rails comes with built-in support for SQLite, which is a lightweight flat-file based database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later. + +Here's the section of the default configuration file with connection information for the development environment: [source, ruby] ------------------------------------------------------- @@ -150,10 +197,10 @@ If you're not running OS X 10.5 or greater, you'll need to install the SQLite ge [source, shell] ------------------------------------------------------- -gem install sqlite3-ruby +$ gem install sqlite3-ruby ------------------------------------------------------- -=== Configuring a MySQL Database +==== Configuring a MySQL Database If you choose to use MySQL, your +config/database.yml+ will look a little different. Here's the development section: @@ -169,7 +216,7 @@ development: ------------------------------------------------------- If your development computer's MySQL installation includes a root user with an empty password, this configuration should work for you. Otherwise, change the username and password in the +development+ section as appropriate. -=== Configuring a PostgreSQL Database +==== Configuring a PostgreSQL Database If you choose to use PostgreSQL, your +config/database.yml+ will be customized to use PostgreSQL databases: @@ -185,21 +232,86 @@ development: Change the username and password in the +development+ section as appropriate. +== Hello, Rails! + +One of the traditional places to start with a new language is by getting some text up on screen quickly. To do that in Rails, you need to create at minimum a controller and a view. Fortunately, you can do that in a single command. Enter this command in your terminal: + +[source, shell] +------------------------------------------------------- +$ script/generate controller home index +------------------------------------------------------- + +TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +script+ commands to Ruby: +ruby script/generate controller home index+. + +Rails will create several files for you, including +app/views/home/index.html.erb+. This is the template that will be used to display the results of the +index+ action (method) in the +home+ controller. Open this file in your text editor and edit it to contain a single line of code: + +[source, html] +------------------------------------------------------- +<h1>Hello, Rails!</h1> +------------------------------------------------------- + +=== Starting up the Web Server + +You actually have a functional Rails application already - after running only two commands! To see it, you need to start a web server on your development machine. You can do this by running another command: + +[source, shell] +------------------------------------------------------- +$ script/server +------------------------------------------------------- + +This will fire up the lightweight Webrick web server by default. To see your application in action, open a browser window and navigate to +http://localhost:3000+. You should see Rails' default information page: + +image:images/rails_welcome.png[Welcome Aboard screenshot] + +TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. In development mode, Rails does not generally require you to stop the server; changes you make in files will be automatically picked up by the server. + +The "Welcome Aboard" page is the smoke test for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. To view the page you just created, navigate to +http://localhost:3000/home/index+. + +=== Setting the Application Home Page + +You'd probably like to replace the "Welcome Aboard" page with your own application's home page. The first step to doing this is to delete the default page from your application: + +[source, shell] +------------------------------------------------------- +$ rm public/index.html +------------------------------------------------------- + +Now, you have to tell Rails where your actual home page is located. Open the file +config/routes.rb+ in your editor. This is your application's, _routing file_, which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. At the bottom of the file you'll see the _default routes_: + +[source, ruby] +------------------------------------------------------- +map.connect ':controller/:action/:id' +map.connect ':controller/:action/:id.:format' +------------------------------------------------------- + +The default routes handle simple requests such as +/home/index+: Rails translates that into a call to the +index+ action in the +home+ controller. As another example, +/posts/edit/1+ would run the +edit+ action in the +posts+ controller with an +id+ of 1. + +To hook up your home page, you need to add another line to the routing file, above the default routes: + +[source, ruby] +------------------------------------------------------- +map.root :controller => "home" +------------------------------------------------------- + +This line illustrates one tiny bit of the "convention over configuration" approach: if you don't specify an action, Rails assumes the +index+ action. + +Now if you navigate to +http://localhost:3000+ in your browser, you'll see the +home/index+ view. + +NOTE: For more information about routing, refer to link:../routing/routing_outside_in.html[Rails Routing from the Outside In]. + == Getting Up and Running Quickly With Scaffolding Rails _scaffolding_ is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job. == Creating a Resource -In the case of the blog application, I'll start by generating a scaffolded Post resource: this will represent a single blog posting. To do this, enter this command in your terminal: +In the case of the blog application, you can start by generating a scaffolded Post resource: this will represent a single blog posting. To do this, enter this command in your terminal: [source, shell] ------------------------------------------------------- -script/generate scaffold Post name:string title:string content:text +$ script/generate scaffold Post name:string title:string content:text ------------------------------------------------------- -TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +script+ commands to Ruby: +ruby script/generate scaffold Post name:string title:string content:text+. - NOTE: While scaffolding will get you up and running quickly, the "one size fits all" code that it generates is unlikely to be a perfect fit for your application. In most cases, you'll need to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch. The scaffold generator will build 13 files in your application, along with some folders, and edit one more. Here's a quick overview of what it creates: @@ -255,33 +367,35 @@ At this point, you need to do two things: create the database and run the migrat [source, shell] ------------------------------------------------------- -rake db:create -rake db:migrate +$ rake db:create +$ rake db:migrate ------------------------------------------------------- NOTE: Because you're working in the development environment by default, both of these commands will apply to the database defined in the +development+ section of your +config/database.yml+ file. -=== Starting the Web Server +=== Adding a Link -You actually have a pretty functional Rails application already - after running only four commands! To see it, you need to start a web server on your development machine. You can do this by running another command: +To hook the posts up to the home page you've already created, you can add a link to the home page. Open +/app/views/home/index.html.erb+ and modify it as follows: -[source, shell] +[source, ruby] ------------------------------------------------------- -script/server +<h1>Hello, Rails!</h1> + +<%= link_to "My Blog", posts_path %> ------------------------------------------------------- -This will fire up the lightweight Webrick web server by default. To see your application in action, open a browser window and navigate to +http://localhost:3000+. You should see Rails' default information page: +The +link_to+ method is one of Rails' built-in view helpers. It creates a hyperlink based on text to display and where to go - in this case, to the path for posts. -image:images/rails_welcome.png[Welcome Aboard screenshot] +=== Working with Posts in the Browser -TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. In development mode, Rails does not generally require you to stop the server; changes you make in files will be automatically picked up by the server. - -The "Welcome Aboard" page is the smoke test for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. But you probably wanted to see something about posts. To do that, navigate to +http://localhost:3000/posts+: +Now you're ready to start working with posts. To do that, navigate to +http://localhost:3000+ and then click the "My Blog" link: image:images/posts_index.png[Posts Index screenshot] This is the result of Rails rendering the +index+ view of your posts. There aren't currently any posts in the database, but if you click the +New Post+ link you can create one. After that, you'll find that you can edit posts, look at their details, or destroy them. All of the logic and HTML to handle this was built by the single +script/generate scaffold+ command. +TIP: In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop and restart the web server. + Congratulations, you're riding the rails! Now it's time to see how it all works. === The Model @@ -296,6 +410,50 @@ end There isn't much to this file - but note that the +Post+ class inherits from +ActiveRecord::Base+. Active Record supplies a great deal of functionality to your Rails models for free, including basic database CRUD (Create, Read, Update, Destroy) operations, data validation, as well as sophisticated search support and the ability to relate multiple models to one another. +=== Adding Some Validation + +Rails includes methods to help you validate the data that you send to models. Open the +app/models/post.rb+ file and edit it: + +[source, ruby] +------------------------------------------------------- +class Comment < ActiveRecord::Base + belongs_to :post + validates_presence_of :commenter, :body + validates_length_of :commenter, :minimum => 5 +end +------------------------------------------------------- + +These changes will ensure that all comments have a body and a commenter, and that the commenter is at least five characters long. Rails can validate a variety of conditions in a model, including the presence or uniqueness of columns, their format, and the existence of associated objects. + +=== Using the Console + +To see your validations in action, you can use the console. The console is a command-line tool that lets you execute Ruby code in the context of your application: + +[source, shell] +------------------------------------------------------- +$ script/console +------------------------------------------------------- + +After the console loads, you can use it to work with your application's models: + +[source, shell] +------------------------------------------------------- +>> c = Comment.create(:body => "A new comment") +=> #<Comment id: nil, commenter: nil, body: "A new comment", +post_id: nil, created_at: nil, updated_at: nil> +>> c.save +=> false +>> c.errors +=> #<ActiveRecord::Errors:0x227be7c @base=#<Comment id: nil, +commenter: nil, body: "A new comment", post_id: nil, created_at: nil, +updated_at: nil>, @errors={"commenter"=>["can't be blank", +"is too short (minimum is 5 characters)"]}> +------------------------------------------------------- + +This code shows creating a new +Comment+ instance, attempting to save it and getting +false+ for a return value (indicating that the save failed), and inspecting the +errors+ of the comment. + +TIP: Unlike the development web server, the console does not automatically load your code afresh for each line. If you make changes, type +reload!+ at the console prompt to load them. + === Listing All Posts The easiest place to start looking at functionality is with the code that lists all posts. Open the file +app/controllers/posts_controller.rb + and look at the +index+ action: @@ -350,10 +508,37 @@ This view iterates over the contents of the +@posts+ array to display content an * +h+ is a Rails helper method to sanitize displayed data, preventing cross-site scripting attacks * +link_to+ builds a hyperlink to a particular destination -* +edit_post_path+ is a helper that Rails provides as part of RESTful routing. +* +edit_post_path+ is a helper that Rails provides as part of RESTful routing. You’ll see a variety of these helpers for the different actions that the controller includes. TIP: For more details on the rendering process, see link:../actionview/layouts_and_rendering [Layouts and Rendering in Rails]. +=== Customizing the Layout + +The view is only part of the story of how HTML is displayed in your web browser. Rails also has the concept of +layouts+, which are containers for views. When Rails renders a view to the browser, it does so by putting the view's HTML into a layout's HTML. The +script/generate scaffold+ command automatically created a default layout, +app/views/layouts/posts.html.erb+, for the posts. Open this layout in your editor and modify the +body+ tag: + +[source, ruby] +------------------------------------------------------- +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> + <title>Posts: <%= controller.action_name %></title> + <%= stylesheet_link_tag 'scaffold' %> +</head> +<body style="background: #EEEEEE;"> + +<p style="color: green"><%= flash[:notice] %></p> + +<%= yield %> + +</body> +</html> +------------------------------------------------------- + +Now when you refresh the +/posts+ page, you'll see a gray background to the page. This same gray background will be used throughout all the views for posts. + === Creating New Posts Creating a new post involves two actions. The first is the +new+ action, which instantiates an empty +Post+ object: @@ -399,7 +584,7 @@ The +new.html.erb+ view displays this empty Post to the user: <%= link_to 'Back', posts_path %> ------------------------------------------------------- -The +form_for+ block is used to create an HTML form. Within this block, you have access to methods to build various controls on the form. For example, +f.text_field :name+ tells Rails to create a text input on the form, and to hook it up to the +name+ attribute of the instance being displayed. +The +form_for+ block is used to create an HTML form. Within this block, you have access to methods to build various controls on the form. For example, +f.text_field :name+ tells Rails to create a text input on the form, and to hook it up to the +name+ attribute of the instance being displayed. Rails uses +form_for+ in preference to having your write raw HTML because the code is more succinct, and because it explicitly ties the form to a particular model instance. When the user clicks the +Create+ button on this form, the browser will send information back to the +create+ method of the controller (Rails knows to call the +create+ method because the form is sent with an HTTP POST request; that's one of the conventions that I mentioned earlier): @@ -531,7 +716,7 @@ end In the +update+ action, Rails first uses the +:id+ parameter passed back from the edit view to locate the database record that's being edited. The +update_attributes+ call then takes the rest of the parameters from the request and applies them to this record. If all goes well, the user is redirected to the post's +show+ view. If there are any problems, it's back to +edit+ to correct them. -NOTE: Sharp-eyed readers will have noticed that the +form_for+ declaration is identical for the +create+ and +edit+ views. Rails generates different code for the two forms because it's smart enough to notice that in the one case it's being passed a new record that has never been saved, and in the other case an existing record that has already been saved to the database. +NOTE: Sharp-eyed readers will have noticed that the +form_for+ declaration is identical for the +create+ and +edit+ views. Rails generates different code for the two forms because it's smart enough to notice that in the one case it's being passed a new record that has never been saved, and in the other case an existing record that has already been saved to the database. In a production Rails application, you would ordinarily eliminate this duplication by moving identical code to a _partial template_, which you could then include in both parent templates. But the scaffold generator tries not to make too many assumptions, and generates code that’s easy to modify if you want different forms for +create+ and +edit+. === Destroying a Post @@ -562,7 +747,7 @@ Models in Rails use a singular name, and their corresponding database tables use [source, shell] ------------------------------------------------------- -script/generate model Comment commenter:string body:text post:references +$ script/generate model Comment commenter:string body:text post:references ------------------------------------------------------- This command will generate four files: @@ -607,7 +792,7 @@ The +t.references+ line sets up a foreign key column for the association between [source, shell] ------------------------------------------------------- -rake db:migrate +$ rake db:migrate ------------------------------------------------------- Rails is smart enough to only execute the migrations that have not already been run against this particular database. @@ -662,7 +847,7 @@ With the model in hand, you can turn your attention to creating a matching contr [source, shell] ------------------------------------------------------- -script/generate controller Comments index show new edit +$ script/generate controller Comments index show new edit ------------------------------------------------------- This creates seven files: @@ -905,6 +1090,7 @@ Now that you've seen your first Rails application, you should feel free to updat http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/2[Lighthouse ticket] +* October 16, 2008: Revised based on feedback from Pratik Naik by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) * October 13, 2008: First complete draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) * October 12, 2008: More detail, rearrangement, editing by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) * September 8, 2008: initial version by James Miller (not yet approved for publication) |