From ec5070c2e2d46c5f209da99bb2f3b455ec02c349 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Fri, 24 Oct 2008 22:13:06 +0530 Subject: Generate new guides --- .../doc/guides/html/actioncontroller_basics.html | 2 +- .../guides/html/getting_started_with_rails.html | 166 +++++++++++++++++++-- .../doc/guides/html/layouts_and_rendering.html | 140 ++++++++++++++++- 3 files changed, 291 insertions(+), 17 deletions(-) (limited to 'railties/doc') diff --git a/railties/doc/guides/html/actioncontroller_basics.html b/railties/doc/guides/html/actioncontroller_basics.html index 9bba0d301a..4057981a0d 100644 --- a/railties/doc/guides/html/actioncontroller_basics.html +++ b/railties/doc/guides/html/actioncontroller_basics.html @@ -331,7 +331,7 @@ http://www.gnu.org/software/src-highlite --> @client = Client.new end -

The Layouts & rendering guide explains this in more detail.

+

The Layouts & rendering guide explains this in more detail.

3. Parameters

diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html index e7be98d34a..c53167a6ac 100644 --- a/railties/doc/guides/html/getting_started_with_rails.html +++ b/railties/doc/guides/html/getting_started_with_rails.html @@ -269,6 +269,16 @@ ul#navMain {
  • + DRYing up the Code + +
  • +
  • Adding a Second Model
      @@ -480,6 +490,24 @@ Transferring representations of the state of that resource between system compon

      For example, to a Rails application a request such as this:

      DELETE /photos/17

      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 makes it even more natural by using conventions to shield you from some of the RESTful complexities.

      +

      If you’d like more details on REST as an architectural style, these resources are more approachable than Fielding’s thesis:

      +
  • 3. Creating a New Rails Project

    @@ -1402,7 +1430,7 @@ http://www.gnu.org/software/src-highlite --> 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. +Sharp-eyed readers will have noticed that the form_for declaration is identical for the new 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.

    6.12. Destroying a Post

    @@ -1424,10 +1452,124 @@ http://www.gnu.org/software/src-highlite -->

    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.

    -

    7. Adding a Second Model

    +

    7. DRYing up the Code

    +
    +

    At this point, it’s worth looking at some of the tools that Rails provides to eliminate duplication in your code. In particular, you can use partials to clean up duplication in views and filters to help with duplication in controllers.

    +

    7.1. Using Partials to Eliminate View Duplication

    +

    As you saw earlier, the scaffold-generated views for the new and edit actions are largely identical. You can pull the shared code out into a partial template. This requires editing the new and edit views, and adding a new template:

    +

    new.html.erb: +[source, ruby]

    +
    +
    +
    <h1>New post</h1>
    +
    +<%= render :partial => "form" %>
    +
    +<%= link_to 'Back', posts_path %>
    +
    +

    edit.html.erb: +[source, ruby]

    +
    +
    +
    <h1>Editing post</h1>
    +
    +<%= render :partial => "form" %>
    +
    +<%= link_to 'Show', @post %> |
    +<%= link_to 'Back', posts_path %>
    +
    +

    _form.html.erb: +[source, ruby]

    +
    +
    +
    <% form_for(@post) do |f| %>
    +  <%= f.error_messages %>
    +
    +  <p>
    +    <%= f.label :name %><br />
    +    <%= f.text_field :name %>
    +  </p>
    +  <p>
    +    <%= f.label :title, "title" %><br />
    +    <%= f.text_field :title %>
    +  </p>
    +  <p>
    +    <%= f.label :content %><br />
    +    <%= f.text_area :content %>
    +  </p>
    +  <p>
    +    <%= f.submit "Save" %>
    +  </p>
    +<% end %>
    +
    +

    Now, when Rails renders the new or edit view, it will insert the _form partial at the indicated point. Note the naming convention for partials: if you refer to a partial named form inside of a view, the corresponding file is _form.html.erb, with a leading underscore.

    +

    For more information on partials, refer to the Layouts and Rending in Rails guide.

    +

    7.2. Using Filters to Eliminate Controller Duplication

    +

    At this point, if you look at the controller for posts, you’ll see some duplication:

    +
    +
    +
    class PostsController < ApplicationController
    +  # ...
    +  def show
    +    @post = Post.find(params[:id])
    +        # ...
    +  end
    +
    +  def edit
    +    @post = Post.find(params[:id])
    +  end
    +
    +  def update
    +    @post = Post.find(params[:id])
    +    # ...
    +  end
    +
    +  def destroy
    +    @post = Post.find(params[:id])
    +    # ...
    +  end
    +end
    +
    +

    Four instances of the exact same line of code doesn’t seem very DRY. Rails provides filters as a way to address this sort of repeated code. In this case, you can DRY things up by using a before_filter:

    +
    +
    +
    class PostsController < ApplicationController
    +  before_filter :find_post, :only => [:show, :edit, :update, :destroy]
    +  # ...
    +  def show
    +        # ...
    +  end
    +
    +  def edit
    +  end
    +
    +  def update
    +    # ...
    +  end
    +
    +  def destroy
    +    # ...
    +  end
    +
    +  private
    +    def find_post
    +      @post = Post.find(params[:id])
    +    end
    +end
    +
    +

    Rails runs before filters before any action in the controller. You can use the :only clause to limit a before filter to only certain actions, or an :except clause to specifically skip a before filter for certain actions. Rails also allows you to define after filters that run after processing an action, as well as around filters that surround the processing of actions. Filters can also be defined in external classes to make it easy to share them between controllers.

    +

    For more information on filters, see the Action Controller Basics guide.

    +
    +

    8. Adding a Second Model

    Now that you've seen what's in a model built with scaffolding, it's time to add a second model to the application. The second model will handle comments on blog posts.

    -

    7.1. Generating a Model

    +

    8.1. 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 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:

    $ rake db:migrate
     

    Rails is smart enough to only execute the migrations that have not already been run against this particular database.

    -

    7.2. Associating Models

    -

    Active Record associations let you declaratively quantify the relationship between two models. In the case of comments and posts, you could write out the relationships this way:

    +

    8.2. Associating Models

    +

    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:

    • @@ -1538,10 +1680,10 @@ http://www.gnu.org/software/src-highlite --> Tip -For more information on Active Record associations, see the Active Record Associations guide. +For more information on Active Record associations, see the Active Record Associations guide.

    -

    7.3. Adding a Route

    +

    8.3. Adding a Route

    Routes are entries in the config/routes.rb file that tell Rails how to match incoming HTTP requests to controller actions. Open up that file and find the existing line referring to posts. Then edit it as follows:

    For more information on routing, see the Rails Routing from the Outside In guide.
    -

    7.4. Generating a Controller

    +

    8.4. Generating a Controller

    With the model in hand, you can turn your attention to creating a matching controller. Again, there's a generator for this:

    @comment = @post.comments.build
     

    This creates a new Comment object and sets up the post_id field to have the id from the specified Post object in a single operation.

    -

    7.5. Building Views

    +

    8.5. Building Views

    Because you skipped scaffolding, you'll need to build views for comments "by hand." Invoking script/generate controller will give you skeleton views, but they'll be devoid of actual content. Here's a first pass at fleshing out the comment views.

    The index.html.erb view:

    @@ -1795,7 +1937,7 @@ http://www.gnu.org/software/src-highlite --> <%= link_to 'Back', post_comments_path(@post) %>

    Again, the added complexity here (compared to the views you saw for managing comments) comes from the necessity of juggling a post and its comments at the same time.

    -

    7.6. Hooking Comments to Posts

    +

    8.6. Hooking Comments to Posts

    As a final step, I'll modify the show.html.erb view for a post to show the comments on that post, and to allow managing those comments:

    Note that each post has its own individual comments collection, accessible as @post.comments. That's a consequence of the declarative associations in the models. Path helpers such as post_comments_path come from the nested route declaration in config/routes.rb.

    -

    8. What's Next?

    +

    9. What's Next?

    Now that you've seen your first Rails application, you should feel free to update it and experiment on your own. But you don't have to do everything without help. As you need assistance getting up and running with Rails, feel free to consult these support resources:

    -

    9. Changelog

    +

    10. Changelog

      diff --git a/railties/doc/guides/html/layouts_and_rendering.html b/railties/doc/guides/html/layouts_and_rendering.html index 916cdd2053..63d060049a 100644 --- a/railties/doc/guides/html/layouts_and_rendering.html +++ b/railties/doc/guides/html/layouts_and_rendering.html @@ -523,7 +523,7 @@ http://www.gnu.org/software/src-highlite -->
      render :file => filename, :content_type => 'application/rss'
       
    The :layout Option
    -

    With most of the options to render, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide. To find the current layout, Rails first looks for a file in app/views/layouts with the same base name as the controller. For example, rendering actions from the PhotosController class will use /app/views/layouts/photos.html.erb. If there is no such controller-specific layout, Rails will use /app/views/layouts/application.html.erb.

    +

    With most of the options to render, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.

    You can use the :layout option to tell Rails to use a specific file as the layout for the current action:

    render :xml => photo, :location => photo_url(photo)
     
    -

    2.2.11. Avoiding Double Render Errors

    +

    2.2.11. Finding Layouts

    +

    To find the current layout, Rails first looks for a file in app/views/layouts with the same base name as the controller. For example, rendering actions from the PhotosController class will use /app/views/layouts/photos.html.erb. If there is no such controller-specific layout, Rails will use /app/views/layouts/application.html.erb. If there is no .erb layout, Rails will use a .builder layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.

    +
    Specifying Layouts on a per-Controller Basis
    +

    You can override the automatic layout conventions in your controllers by using the layout declaration in the controller. For example:

    +
    +
    +
    class ProductsController < ApplicationController
    +  layout "inventory"
    +  #...
    +end
    +
    +

    With this declaration, all methods within ProductsController will use app/views/layouts/inventory.html.erb for their layout.

    +

    To assign a specific layout for the entire application, use a declaration in your ApplicationController class:

    +
    +
    +
    class ApplicationController < ActionController::Base
    +  layout "main"
    +  #...
    +end
    +
    +

    With this declaration, all views in the entire application will use app/views/layouts/main.html.erb for their layout.

    +
    Choosing Layouts at Runtime
    +

    You can use a symbol to defer the choice of layout until a request is processed:

    +
    +
    +
    class ProductsController < ApplicationController
    +  layout :products_layout
    +
    +  def show
    +    @product = Product.find(params[:id])
    +  end
    +
    +  private
    +    def products_layout
    +      @current_user.special? ? "special" : "products"
    +    end
    +
    +end
    +
    +

    Now, if the current user is a special user, they'll get a special layout when viewing a product. You can even use an inline method to determine the layout:

    +
    +
    +
    class ProductsController < ApplicationController
    +  layout proc{ |controller| controller.
    +  # ...
    +end
    +
    +
    Conditional Layouts
    +

    Layouts specified at the controller level support :only and :except options that take either a method name or an array of method names:

    +
    +
    +
    class ProductsController < ApplicationController
    +  layout "inventory", :only => :index
    +  layout "product", :except => [:index, :rss]
    +  #...
    +end
    +
    +

    With those declarations, the inventory layout would be used only for the index method, the product layout would be used for everything else except the rss method, and the rss method will have its layout determined by the automatic layout rules.

    +
    Layout Inheritance
    +

    Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:

    +
    +
    +
    class ApplicationController < ActionController::Base
    +  layout "main"
    +  #...
    +end
    +
    +class PostsController < ApplicationController
    +  # ...
    +end
    +
    +class SpecialPostsController < PostsController
    +  layout "special"
    +  # ...
    +end
    +
    +class OldPostsController < SpecialPostsController
    +  layout nil
    +
    +  def show
    +    @post = Post.find(params[:id])
    +  end
    +
    +  def index
    +    @old_posts = Post.older
    +    render :layout => "old"
    +  end
    +  # ...
    +end
    +
    +

    In this application:

    +
    +

    2.2.12. Avoiding Double Render Errors

    Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that render works.

    For example, here's some code that will trigger this error:

    @@ -666,8 +799,7 @@ http://www.gnu.org/software/src-highlite -->

    3. Structuring Layouts

    -

    When Rails renders a view as a response, it does so by combining the view with the current layout. To find the current layout, Rails first looks for a file in app/views/layouts with the same base name as the controller. For example, rendering actions from the PhotosController class will use /app/views/layouts/photos.html.erb. If there is no such controller-specific layout, Rails will use /app/views/layouts/application.html.erb. You can also specify a particular layout by using the :layout option to render.

    -

    Within a layout, you have access to three tools for combining different bits of output to form the overall response:

    +

    When Rails renders a view as a response, it does so by combining the view with the current layout (using the rules for finding the current layout that were covered earlier in this guide). Within a layout, you have access to three tools for combining different bits of output to form the overall response:

    • -- cgit v1.2.3