diff options
Diffstat (limited to 'railties/guides/source/getting_started.textile')
-rw-r--r-- | railties/guides/source/getting_started.textile | 347 |
1 files changed, 172 insertions, 175 deletions
diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 0b89021392..fe43c9db36 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -41,8 +41,15 @@ internet for learning Ruby, including: * "Programming Ruby":http://www.ruby-doc.org/docs/ProgrammingRuby/ * "Why's (Poignant) Guide to Ruby":http://mislav.uniqpath.com/poignant-guide/ +Also, the example code for this guide is available in the rails github:https://github.com/rails/rails repository +in rails/railties/guides/code/getting_started. + h3. What is Rails? +TIP: This section goes into the background and philosophy of the Rails framework +in detail. You can safely skip this section and come back to it at a later time. +Section 3 starts you on the path to creating your first Rails application. + Rails is a web application development framework written in the Ruby language. It is designed to make programming web applications easier by making assumptions about what every developer needs to get started. It allows you to write less @@ -61,9 +68,9 @@ The Rails philosophy includes several guiding principles: * DRY - "Don't Repeat Yourself" - suggests that writing the same code over and over again is a bad thing. * Convention Over Configuration - means that Rails makes assumptions about what you want to do and how you're going to -d o it, rather than requiring you to specify every little thing through endless configuration files. +do it, rather than requiring you to specify every little thing through endless configuration files. * REST is the best pattern for web applications - organizing your application around resources and standard HTTP verbs -i s the fastest way to go. +is the fastest way to go. h4. The MVC Architecture @@ -116,7 +123,6 @@ need to know anything about them to continue with this guide. * Active Support * Railties - h5. Action Pack Action Pack is a single gem that contains Action Controller, Action View and @@ -197,9 +203,10 @@ For example, the following HTTP request: <tt>DELETE /photos/17</tt> -refers to a photo resource with an ID of 17 and indicates an action to be taken -upon it: deletion. REST is a natural web application architecture which Rails -abstracts, shielding you from RESTful complexities and browser quirks. +would be understood to refer to a photo resource with the ID of 17, and to +indicate a desired action - deleting that resource. REST is a natural style for +the architecture of web applications, and Rails hooks into this shielding you +from many of the RESTful complexities and browser quirks. If you'd like more details on REST as an architectural style, these resources are more approachable than Fielding's thesis: @@ -212,7 +219,11 @@ Ian Robinson h3. Creating a New Rails Project -If you follow this guide, you'll create a Rails project called <tt>blog</tt>, a +The best way to use this guide is to follow each step as it happens, no code or +step needed to make this example application has been left out, so you can +literally follow along step by step. You can get the complete code "here":https://github.com/lifo/docrails/tree/master/railties/guides/code/getting_started. + +By following along with this guide, you'll create a Rails project called <tt>blog</tt>, a (very) simple weblog. Before you can start building the application, you need to make sure that you have Rails itself installed. @@ -230,13 +241,16 @@ Usually run this as the root user: TIP. If you're working on Windows, you can quickly install Ruby and Rails with "Rails Installer":http://railsinstaller.org. -h4. Creating the Blog Application +To verify that you have everything installed correctly, you should be able to run +the following: -The best way to use this guide is to follow each step as it happens, no code or -step needed to make this example application has been left out, so you can -literally follow along step by step. If you need to see the completed code, you -can download it from "Getting Started -Code":https://github.com/mikel/getting-started-code. +<shell> +$ rails --version +</shell> + +If it says something like "Rails 3.1.3" you are ready to continue. + +h4. Creating the Blog Application To begin, open a terminal, navigate to a folder where you have rights to create files, and type: @@ -258,41 +272,50 @@ directly in that application: $ cd blog </shell> -In any case, Rails will create a folder in your working directory called -<tt>blog</tt>. Open up that folder and explore its contents. Most of the work in +The 'rails new blog' command we ran above created a folder in your working directory +called <tt>blog</tt>. The <tt>blog</tt> folder has a number of auto-generated folders +that make up the structure of a Rails application. Most of the work in this tutorial will happen in the <tt>app/</tt> folder, but here's a basic -rundown on the function of each folder that Rails creates in a new application -by default: +rundown on the function of each of the files and folders that Rails created by default: |_.File/Folder|_.Purpose| -|Gemfile|This file allows you to specify what gem dependencies are needed for your Rails application. See section on Bundler, below.| -|README|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.| -|Rakefile|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.| |app/|Contains the controllers, models, views and assets for your application. You'll focus on this folder for the remainder of this guide.| -|config/|Configure your application's runtime rules, routes, database, and more.| +|config/|Configure your application's runtime rules, routes, database, and more. This is covered in more detail in "Configuring Rails Applications":configuring.html| |config.ru|Rack configuration for Rack based servers used to start the application.| -|db/|Shows your current database schema, as well as the database migrations. You'll learn about migrations shortly.| +|db/|Contains your current database schema, as well as the database migrations.| |doc/|In-depth documentation for your application.| -|lib/|Extended modules for your application (not covered in this guide).| +|Gemfile<BR />Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application.| +|lib/|Extended modules for your application.| |log/|Application log files.| |public/|The only folder seen to the world as-is. Contains the static files and compiled assets.| +|Rakefile|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.| +|README|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.| |script/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.| |test/|Unit tests, fixtures, and other test apparatus. These are covered in "Testing Rails Applications":testing.html| |tmp/|Temporary files| -|vendor/|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.| +|vendor/|A place for all third-party code. In a typical Rails application, this includes Ruby Gems, the Rails source code (if you optionally install it into your project) and plugins containing additional prepackaged functionality.| h4. Configuring a Database 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 SQLite3. The file contains sections for three different +configured to use SQLite3. 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 +development+ environment is used on your development/local computer as you interact +manually with the application. +* The +test+ environment is used when running automated tests. * The +production+ environment is used when you deploy your application for the world to use. +TIP: You don't have to update the database configurations manually. If you look at the +options of the application generator, you will see that one of the options +is named <tt>--database</tt>. This option allows you to choose an adapter from a +list of the most used relational databases. You can even run the generator +repeatedly: <tt>cd .. && rails new blog --database=mysql</tt>. When you confirm the overwriting + of the +config/database.yml+ file, your application will be configured for MySQL +instead of SQLite. Detailed examples of the common database connections are below. + h5. Configuring an SQLite3 Database Rails comes with built-in support for "SQLite3":http://www.sqlite.org, which is @@ -357,7 +380,7 @@ development: h5. Configuring an SQLite3 Database for JRuby Platform -If you choose to use SQLite3 and using JRuby, your +config/database.yml+ will +If you choose to use SQLite3 and are using JRuby, your +config/database.yml+ will look a little different. Here's the development section: <yaml> @@ -368,7 +391,7 @@ development: h5. Configuring a MySQL Database for JRuby Platform -If you choose to use MySQL and using JRuby, your +config/database.yml+ will look +If you choose to use MySQL and are using JRuby, your +config/database.yml+ will look a little different. Here's the development section: <yaml> @@ -381,7 +404,7 @@ development: h5. Configuring a PostgreSQL Database for JRuby Platform -Finally if you choose to use PostgreSQL and using JRuby, your +Finally if you choose to use PostgreSQL and are using JRuby, your +config/database.yml+ will look a little different. Here's the development section: @@ -396,14 +419,6 @@ development: Change the username and password in the +development+ section as appropriate. -TIP: You don't have to update the database configurations manually. If you look at the -options of the application generator, you will see that one of the options -is named <tt>--database</tt>. This option allows you to choose an adapter from a -list of the most used relational databases. You can even run the generator -repeatedly: <tt>cd .. && rails new blog --database=mysql</tt>. When you confirm the overwriting - of the +config/database.yml+ file, your application will be configured for MySQL -instead of SQLite. - h4. Creating the Database Now that you have your database configured, it's time to have Rails create an @@ -435,6 +450,8 @@ start a web server on your development machine. You can do this by running: $ rails server </shell> +TIP: Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the absence of a runtime will give you an +execjs+ error. Usually Mac OS X and Windows come with a JavaScript runtime installed. +therubyracer+ and +therubyrhino+ are the commonly used runtimes for Ruby and JRuby respectively. You can also investigate a list of runtimes at "ExecJS":https://github.com/sstephenson/execjs. + This will fire up an instance of the WEBrick web server by default (Rails can also use several other web servers). To see your application in action, open a browser window and navigate to "http://localhost:3000":http://localhost:3000. @@ -477,7 +494,7 @@ Open this file in your text editor and edit it to contain a single line of code: h4. Setting the Application Home Page Now that we have made the controller and view, we need to tell Rails when we -want "Hello Rails" to show up. In our case, we want it to show up when we +want "Hello Rails!" to show up. In our case, we want it to show up when we navigate to the root URL of our site, "http://localhost:3000":http://localhost:3000, instead of the "Welcome Aboard" smoke test. @@ -498,8 +515,7 @@ file_ which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. This file contains many sample routes on commented lines, and one of them actually shows you how to connect the root of your site to a specific controller and action. -Find the line beginning with +root :to+, uncomment it and change it like the -following: +Find the line beginning with +root :to+ and uncomment it. It should look something like the following: <ruby> Blog::Application.routes.draw do @@ -527,7 +543,7 @@ resource in a single operation, scaffolding is the tool for the job. h3. Creating a Resource -In the case of the blog application, you can start by generating a scaffolded +In the case of the blog application, you can start by generating a scaffold for the Post resource: this will represent a single blog posting. To do this, enter this command in your terminal: @@ -535,40 +551,36 @@ command in your terminal: $ rails generate scaffold Post name:string title:string content:text </shell> -This will create a new database table called posts (plural of Post). The table -will have three columns, name (type string), title (type string) and content -(type text). It will also hook this new database up to Rails (details below). - -NOTE. While scaffolding will get you up and running quickly, the code it -generates is unlikely to be a perfect fit for your application. You'll most -probably want to customize the generated code. Many experienced Rails developers -avoid scaffolding entirely, preferring to write all or most of their source code -from scratch. Rails, however, makes it really simple to customize templates for -generated models, controllers, views and other source files. You'll find more -information in the "Creating and Customizing Rails Generators & -Templates":generators.html guide. - -The scaffold generator will build 17 files in your application, along with some -folders, and edit one more. Here's a quick overview of what it creates: +The scaffold generator will build several files in your application, along with some +folders, and edit <tt>config/routes.rb</tt>. Here's a quick overview of what it creates: |_.File |_.Purpose| |db/migrate/20100207214725_create_posts.rb |Migration to create the posts table in your database (your name will include a different timestamp)| |app/models/post.rb |The Post model| -|test/fixtures/posts.yml |Dummy posts for use in testing| +|test/unit/post_test.rb |Unit testing harness for the posts model| +|test/fixtures/posts.yml |Sample posts for use in testing| +|config/routes.rb |Edited to include routing information for posts| |app/controllers/posts_controller.rb |The Posts controller| |app/views/posts/index.html.erb |A view to display an index of all posts | |app/views/posts/edit.html.erb |A view to edit an existing post| |app/views/posts/show.html.erb |A view to display a single post| |app/views/posts/new.html.erb |A view to create a new post| |app/views/posts/_form.html.erb |A partial to control the overall look and feel of the form used in edit and new views| -|app/helpers/posts_helper.rb |Helper functions to be used from the post views| -|app/assets/stylesheets/scaffold.css.scss |Cascading style sheet to make the scaffolded views look better| -|app/assets/stylesheets/post.css.scss |Cascading style sheet for the posts controller| -|app/assets/javascripts/post.js.coffee |CoffeeScript for the posts controller| -|test/unit/post_test.rb |Unit testing harness for the posts model| |test/functional/posts_controller_test.rb |Functional testing harness for the posts controller| +|app/helpers/posts_helper.rb |Helper functions to be used from the post views| |test/unit/helpers/posts_helper_test.rb |Unit testing harness for the posts helper| -|config/routes.rb |Edited to include routing information for posts| +|app/assets/javascripts/posts.js.coffee |CoffeeScript for the posts controller| +|app/assets/stylesheets/posts.css.scss |Cascading style sheet for the posts controller| +|app/assets/stylesheets/scaffolds.css.scss |Cascading style sheet to make the scaffolded views look better| + +NOTE. While scaffolding will get you up and running quickly, the code it +generates is unlikely to be a perfect fit for your application. You'll most +probably want to customize the generated code. Many experienced Rails developers +avoid scaffolding entirely, preferring to write all or most of their source code +from scratch. Rails, however, makes it really simple to customize templates for +generated models, controllers, views and other source files. You'll find more +information in the "Creating and Customizing Rails Generators & +Templates":generators.html guide. h4. Running a Migration @@ -596,12 +608,12 @@ class CreatePosts < ActiveRecord::Migration end </ruby> -The above migration creates a method name +change+ which will be called when you -run this migration. The action defined in that method is also reversible, which +The above migration creates a method named +change+ which will be called when you +run this migration. The action defined in this method is also reversible, which means Rails knows how to reverse the change made by this migration, in case you -want to reverse it at later date. By default, when you run this migration it -will creates a +posts+ table with two string columns and a text column. It also -creates two timestamp fields to track record creation and updating. More +want to reverse it later. When you run this migration it will create a ++posts+ table with two string columns and a text column. It also creates two +timestamp fields to allow Rails to track post creation and update times. More information about Rails migrations can be found in the "Rails Database Migrations":migrations.html guide. @@ -623,7 +635,7 @@ table. NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your -+config/database.yml+ file. If you would like to execute migrations in other ++config/database.yml+ file. If you would like to execute migrations in another environment, for instance in production, you must explicitly pass it when invoking the command: <tt>rake db:migrate RAILS_ENV=production</tt>. @@ -692,7 +704,8 @@ end These changes will ensure that all posts have a name and a title, and that the title 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. +format, and the existence of associated objects. Validations are covered in detail +in "Active Record Validations and Callbacks":active_record_validations_callbacks.html#validations-overview h4. Using the Console @@ -705,8 +718,8 @@ $ rails console </shell> TIP: The default console will make changes to your database. You can instead -open a console that will roll back any changes you make by using +rails console ---sandbox+. +open a console that will roll back any changes you make by using <tt>rails console +--sandbox</tt>. After the console loads, you can use it to work with your application's models: @@ -717,10 +730,8 @@ After the console loads, you can use it to work with your application's models: updated_at: nil> >> p.save => false ->> p.errors -=> #<OrderedHash { :title=>["can't be blank", - "is too short (minimum is 5 characters)"], - :name=>["can't be blank"] }> +>> p.errors.full_messages +=> ["Name can't be blank", "Title can't be blank", "Title is too short (minimum is 5 characters)"] </shell> This code shows creating a new +Post+ instance, attempting to save it and @@ -730,13 +741,14 @@ inspecting the +errors+ of the post. When you're finished, type +exit+ and hit +return+ to exit the console. TIP: Unlike the development web server, the console does not automatically load -your code afresh for each line. If you make changes to your models while the -console is open, type +reload!+ at the console prompt to load them. +your code afresh for each line. If you make changes to your models (in your editor) +while the console is open, type +reload!+ at the console prompt to load them. h4. 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 +Let's dive into the Rails code a little deeper to see how the application is +showing us the list of Posts. Open the file ++app/controllers/posts_controller.rb+ and look at the +index+ action: <ruby> @@ -750,9 +762,8 @@ def index end </ruby> -+Post.all+ calls the +Post+ model to return all of the posts currently in the -database. The result of this call is an array of posts that we store in an -instance variable called +@posts+. ++Post.all+ returns all of the posts currently in the database as an array +of +Post+ records that we store in an instance variable called +@posts+. TIP: For more information on finding records with Active Record, see "Active Record Query Interface":active_record_querying.html. @@ -784,7 +795,8 @@ Here's +app/views/posts/index.html.erb+: <td><%= post.content %></td> <td><%= link_to 'Show', post %></td> <td><%= link_to 'Edit', edit_post_path(post) %></td> - <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td> + <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', + :method => :delete %></td> </tr> <% end %> </table> @@ -802,7 +814,7 @@ and links. A few things to note in the view: NOTE. In previous versions of Rails, you had to use +<%=h post.name %>+ so that any HTML would be escaped before being inserted into the page. In Rails -3.0, this is now the default. To get unescaped HTML, you now use +<%= raw +3.0+, this is now the default. To get unescaped HTML, you now use +<%= raw post.name %>+. TIP: For more details on the rendering process, see "Layouts and Rendering in @@ -816,17 +828,18 @@ Rails renders a view to the browser, it does so by putting the view's HTML into a layout's HTML. In previous versions of Rails, the +rails generate scaffold+ command would automatically create a controller specific layout, like +app/views/layouts/posts.html.erb+, for the posts controller. However this has -been changed in Rails 3.0. An application specific +layout+ is used for all the +been changed in Rails 3.0+. An application specific +layout+ is used for all the controllers and can be found in +app/views/layouts/application.html.erb+. Open -this layout in your editor and modify the +body+ tag: +this layout in your editor and modify the +body+ tag to include the style directive +below: <erb> <!DOCTYPE html> <html> <head> <title>Blog</title> - <%= stylesheet_link_tag :all %> - <%= javascript_include_tag :defaults %> + <%= stylesheet_link_tag "application" %> + <%= javascript_include_tag "application" %> <%= csrf_meta_tags %> </head> <body style="background: #EEEEEE;"> @@ -868,10 +881,10 @@ The +new.html.erb+ view displays this empty Post to the user: The +<%= render 'form' %>+ line is our first introduction to _partials_ in Rails. A partial is a snippet of HTML and Ruby code that can be reused in -multiple locations. In this case, the form used to make a new post, is basically -identical to a form used to edit a post, both have text fields for the name and -title and a text area for the content with a button to make a new post or update -the existing post. +multiple locations. In this case, the form used to make a new post is basically +identical to the form used to edit a post, both having text fields for the name and +title, a text area for the content, and a button to create the new post or to update +the existing one. If you take a look at +views/posts/_form.html.erb+ file, you will see the following: @@ -880,7 +893,8 @@ following: <%= form_for(@post) do |f| %> <% if @post.errors.any? %> <div id="errorExplanation"> - <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2> + <h2><%= pluralize(@post.errors.count, "error") %> prohibited + this post from being saved:</h2> <ul> <% @post.errors.full_messages.each do |msg| %> <li><%= msg %></li> @@ -908,15 +922,15 @@ following: </erb> This partial receives all the instance variables defined in the calling view -file, so in this case, the controller assigned the new Post object to +@post+ -and so, this is available in both the view and partial as +@post+. +file. In this case, the controller assigned the new +Post+ object to +@post+, +which will thus be available in both the view and the partial as +@post+. For more information on partials, refer to the "Layouts and Rendering in Rails":layouts_and_rendering.html#using-partials guide. 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 ++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. You can only use these methods with attributes of the model that the form is based on (in this case +name+, +title+, and +content+). Rails uses +form_for+ in preference to @@ -932,9 +946,9 @@ to a model, you should use the +form_tag+ method, which provides shortcuts for building forms that are not necessarily tied to a model instance. When the user clicks the +Create Post+ 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): +send information back to the +create+ action of the controller (Rails knows to +call the +create+ action because the form is sent with an HTTP POST request; +that's one of the conventions that were mentioned earlier): <ruby> def create @@ -966,12 +980,12 @@ If the post was not successfully saved, due to a validation error, then the controller returns the user back to the +new+ action with any error messages so that the user has the chance to fix the error and try again. -The "Post was successfully created." message is stored inside of the Rails -+flash+ hash, (usually just called _the flash_) so that messages can be carried +The "Post was successfully created." message is stored in the Rails ++flash+ hash (usually just called _the flash_), so that messages can be carried over to another action, providing the user with useful information on the status of their request. In the case of +create+, the user never actually sees any page -rendered during the Post creation process, because it immediately redirects to -the new Post as soon Rails saves the record. The Flash carries over a message to +rendered during the post creation process, because it immediately redirects to +the new +Post+ as soon as Rails saves the record. The Flash carries over a message to the next action, so that when the user is redirected back to the +show+ action, they are presented with a message saying "Post was successfully created." @@ -995,7 +1009,7 @@ end The +show+ action uses +Post.find+ to search for a single record in the database by its id value. After finding the record, Rails displays it by using -+show.html.erb+: ++app/views/posts/show.html.erb+: <erb> <p class="notice"><%= notice %></p> @@ -1044,9 +1058,9 @@ it: <%= link_to 'Back', posts_path %> </erb> -Again, as with the +new+ action, the +edit+ action is using the +form+ partial, -this time however, the form will do a PUT action to the PostsController and the -submit button will display "Update Post" +Again, as with the +new+ action, the +edit+ action is using the +form+ partial. +This time, however, the form will do a PUT action to the +PostsController+ and the +submit button will display "Update Post". Submitting the form created by this view will invoke the +update+ action within the controller: @@ -1059,7 +1073,7 @@ def update if @post.update_attributes(params[:post]) format.html { redirect_to(@post, :notice => 'Post was successfully updated.') } - format.json { render :json => {}, :status => :ok } + format.json { head :no_content } else format.html { render :action => "edit" } format.json { render :json => @post.errors, @@ -1071,9 +1085,9 @@ 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 the +edit+ view to ++update_attributes+ call then takes the +post+ parameter (a hash) from the request +and applies it to this record. If all goes well, the user is redirected to the +post's +show+ action. If there are any problems, it redirects back to the +edit+ action to correct them. h4. Destroying a Post @@ -1087,20 +1101,20 @@ def destroy @post.destroy respond_to do |format| - format.html { redirect_to(posts_url) } - format.json { render :json => {}, :status => :ok } + format.html { redirect_to posts_url } + format.json { head :no_content } end end </ruby> The +destroy+ method of an Active Record model instance removes the corresponding record from the database. After that's done, there isn't any -record to display, so Rails redirects the user's browser to the index view for -the model. +record to display, so Rails redirects the user's browser to the index action of +the controller. h3. Adding a Second Model -Now that you've seen how a model built with scaffolding looks like, it's time to +Now that you've seen what a model built with scaffolding looks like, it's time to add a second model to the application. The second model will handle comments on blog posts. @@ -1108,7 +1122,7 @@ h4. Generating a Model Models in Rails use a singular name, and their corresponding database tables use a plural name. For the model to hold comments, the convention is to use the name -Comment. Even if you don't want to use the entire apparatus set up by ++Comment+. Even if you don't want to use the entire apparatus set up by scaffolding, most Rails developers still use generators to make things like models and controllers. To create the new model, run this command in your terminal: @@ -1119,9 +1133,11 @@ $ rails generate model Comment commenter:string body:text post:references This command will generate four files: -* +app/models/comment.rb+ - The model -* +db/migrate/20100207235629_create_comments.rb+ - The migration -* +test/unit/comment_test.rb+ and +test/fixtures/comments.yml+ - The test harness. +|_.File |_.Purpose| +|db/migrate/20100207235629_create_comments.rb | Migration to create the comments table in your database (your name will include a different timestamp) | +| app/models/comment.rb | The Comment model | +| test/unit/comment_test.rb | Unit testing harness for the comments model | +| test/fixtures/comments.yml | Sample comments for use in testing | First, take a look at +comment.rb+: @@ -1168,8 +1184,10 @@ run against the current database, so in this case you will just see: <shell> == CreateComments: migrating ================================================= -- create_table(:comments) - -> 0.0017s -== CreateComments: migrated (0.0018s) ======================================== + -> 0.0008s +-- add_index(:comments, :post_id) + -> 0.0003s +== CreateComments: migrated (0.0012s) ======================================== </shell> h4. Associating Models @@ -1178,8 +1196,8 @@ Active Record associations let you easily declare the relationship between two models. In the case of comments and posts, you could write out the relationships this way: -* Each comment belongs to one post -* One post can have many comments +* Each comment belongs to one post. +* One post can have many comments. In fact, this is very close to the syntax that Rails uses to declare this association. You've already seen the line of code inside the Comment model that @@ -1205,7 +1223,7 @@ end These two declarations enable a good bit of automatic behavior. For example, if you have an instance variable +@post+ containing a post, you can retrieve all -the comments belonging to that post as the array +@post.comments+. +the comments belonging to that post as an array using +@post.comments+. TIP: For more information on Active Record associations, see the "Active Record Associations":association_basics.html guide. @@ -1214,9 +1232,9 @@ h4. Adding a Route for Comments As with the +home+ controller, we will need to add a route so that Rails knows where we would like to navigate to see +comments+. Open up the -+config/routes.rb+ file again, you will see an entry that was added -automatically for +posts+ near the top by the scaffold generator, +resources -:posts+, edit it as follows: ++config/routes.rb+ file again. Near the top, you will see the entry for +posts+ +that was added automatically by the scaffold generator: <tt>resources +:posts</tt>. Edit it as follows: <ruby> resources :posts do @@ -1242,19 +1260,20 @@ $ rails generate controller Comments This creates six files and one empty directory: -* +app/controllers/comments_controller.rb+ - The controller -* +app/helpers/comments_helper.rb+ - A view helper file -* +test/functional/comments_controller_test.rb+ - The functional tests for the controller -* +test/unit/helpers/comments_helper_test.rb+ - The unit tests for the helper -* +app/views/comments/+ - Views of the controller are stored here -* +app/assets/stylesheets/comment.css.scss+ - Cascading style sheet for the controller -* +app/assets/javascripts/comment.js.coffee+ - CoffeeScript for the controller +|_.File/Directory |_.Purpose | +| app/controllers/comments_controller.rb | The Comments controller | +| app/views/comments/ | Views of the controller are stored here | +| test/functional/comments_controller_test.rb | The functional tests for the controller | +| app/helpers/comments_helper.rb | A view helper file | +| test/unit/helpers/comments_helper_test.rb | The unit tests for the helper | +| app/assets/javascripts/comment.js.coffee | CoffeeScript for the controller | +| app/assets/stylesheets/comment.css.scss | Cascading style sheet for the controller | Like with any blog, our readers will create their comments directly after reading the post, and once they have added their comment, will be sent back to the post show page to see their comment now listed. Due to this, our +CommentsController+ is there to provide a method to create comments and delete -SPAM comments when they arrive. +spam comments when they arrive. So first, we'll wire up the Post show template (+/app/views/posts/show.html.erb+) to let us make a new comment: @@ -1296,8 +1315,8 @@ So first, we'll wire up the Post show template <%= link_to 'Back to Posts', posts_path %> | </erb> -This adds a form on the Post show page that creates a new comment, which will -call the +CommentsController+ +create+ action, so let's wire that up: +This adds a form on the +Post+ show page that creates a new comment by +calling the +CommentsController+ +create+ action. Let's wire that up: <ruby> class CommentsController < ApplicationController @@ -1310,9 +1329,9 @@ end </ruby> You'll see a bit more complexity here than you did in the controller for posts. -That's a side-effect of the nesting that you've set up; each request for a +That's a side-effect of the nesting that you've set up. Each request for a comment has to keep track of the post to which the comment is attached, thus the -initial find action to the Post model to get the post in question. +initial call to the +find+ method of the +Post+ model to get the post in question. In addition, the code takes advantage of some of the methods available for an association. We use the +create+ method on +@post.comments+ to create and save @@ -1382,9 +1401,9 @@ right places. h3. Refactoring -Now that we have Posts and Comments working, if we take a look at the -+app/views/posts/show.html.erb+ template, it's getting long and awkward. We can -use partials to clean this up. +Now that we have posts and comments working, take a look at the ++app/views/posts/show.html.erb+ template. It is getting long and awkward. We can +use partials to clean it up. h4. Rendering Partial Collections @@ -1404,7 +1423,7 @@ following into it: </p> </erb> -Then in the +app/views/posts/show.html.erb+ you can change it to look like the +Then you can change +app/views/posts/show.html.erb+ to look like the following: <erb> @@ -1457,8 +1476,8 @@ comment to a local variable named the same as the partial, in this case h4. Rendering a Partial Form -Lets also move that new comment section out to it's own partial, again, you -create a file +app/views/comments/_form.html.erb+ and in it you put: +Let us also move that new comment section out to its own partial. Again, you +create a file +app/views/comments/_form.html.erb+ containing: <erb> <%= form_for([@post, @post.comments.build]) do |f| %> @@ -1509,7 +1528,7 @@ Then you make the +app/views/posts/show.html.erb+ look like the following: </erb> The second render just defines the partial template we want to render, -<tt>comments/form</tt>, Rails is smart enough to spot the forward slash in that +<tt>comments/form</tt>. Rails is smart enough to spot the forward slash in that string and realize that you want to render the <tt>_form.html.erb</tt> file in the <tt>app/views/comments</tt> directory. @@ -1518,7 +1537,7 @@ defined it as an instance variable. h3. Deleting Comments -Another important feature on a blog is being able to delete SPAM comments. To do +Another important feature of a blog is being able to delete spam comments. To do this, we need to implement a link of some sort in the view and a +DELETE+ action in the +CommentsController+. @@ -1608,7 +1627,7 @@ action, except for +index+ and +show+, so we write that: <ruby> class PostsController < ApplicationController - http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index + http_basic_authenticate_with :name => "dhh", :password => "secret", :except => [:index, :show] # GET /posts # GET /posts.json @@ -1636,7 +1655,6 @@ Authentication challenge !images/challenge.png(Basic HTTP Authentication Challenge)! - h3. Building a Multi-Model Form Another feature of your average blog is the ability to tag posts. To implement @@ -1724,8 +1742,8 @@ This example shows another option of the render helper, being able to pass in local variables, in this case, we want the local variable +form+ in the partial to refer to the +post_form+ object. -We also add a <tt>@post.tags.build</tt> at the top of this form, this is to make -sure there is a new tag ready to have it's name filled in by the user. If you do +We also add a <tt>@post.tags.build</tt> at the top of this form. This is to make +sure there is a new tag ready to have its name filled in by the user. If you do not build the new tag, then the form will not appear as there is no new Tag object ready to create. @@ -1890,24 +1908,3 @@ Two very common sources of data that are not UTF-8: is using Latin-1 internally, and your user enters a Russian, Hebrew, or Japanese character, the data will be lost forever once it enters the database. If possible, use UTF-8 as the internal storage of your database. - -h3. Changelog - -* April 26, 2011: Change migration code from +up+, +down+ pair to +change+ method by "Prem Sichanugrist":http://sikachu.com -* April 11, 2011: Change scaffold_controller generator to create format block for JSON instead of XML by "Sebastian Martinez":http://www.wyeworks.com -* August 30, 2010: Minor editing after Rails 3 release by "Joost Baaij":http://www.spacebabies.nl -* July 12, 2010: Fixes, editing and updating of code samples by "Jaime Iniesta":http://jaimeiniesta.com -* May 16, 2010: Added a section on configuration gotchas to address common encoding problems that people might have by "Yehuda Katz":http://www.yehudakatz.com -* April 30, 2010: Fixes, editing and updating of code samples by "Rohit Arondekar":http://rohitarondekar.com -* April 25, 2010: Couple of more minor fixups by "Mikel Lindsaar":credits.html#raasdnil -* April 1, 2010: Fixed document to validate XHTML 1.0 Strict by "Jaime Iniesta":http://jaimeiniesta.com -* February 8, 2010: Full re-write for Rails 3.0-beta, added helpers and before_filters, refactored code by "Mikel Lindsaar":credits.html#raasdnil -* January 24, 2010: Re-write for Rails 3.0 by "Mikel Lindsaar":credits.html#raasdnil -* July 18, 2009: Minor cleanup in anticipation of Rails 2.3.3 by "Mike Gunderloy":credits.html#mgunderloy -* February 1, 2009: Updated for Rails 2.3 by "Mike Gunderloy":credits.html#mgunderloy -* November 3, 2008: Formatting patch from Dave Rothlisberger -* November 1, 2008: First approved version by "Mike Gunderloy":credits.html#mgunderloy -* October 16, 2008: Revised based on feedback from Pratik Naik by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) -* October 13, 2008: First complete draft by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) -* October 12, 2008: More detail, rearrangement, editing by "Mike Gunderloy":credits.html#mgunderloy (not yet approved for publication) -* September 8, 2008: initial version by "James Miller":credits.html#bensie (not yet approved for publication) |