`
sillycat
  • 浏览: 2502341 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Rails Study(IV)Layouts and Rendering in Rails

阅读更多
Rails Study(IV)Layouts and Rendering in Rails

1. Overview: How the Pieces Fit Together
The Controller hands things off to the View, and it normally hands off any heavy code to the Model.

2. Creating Responses
From the controller's point of view, there are three ways to create an HTTP response:
* call render to create a full response to send back to the browser
* call redirect_to to send an HTTP redirect status code to the browser
* call head to create a response consisting solely of HTTP headers to send back to the browser

2.1 Rendering by Default: Convention Over Configuration in Action
class BooksController < ApplicationController
end

resources :books

app/views/books/index.html.erb

URL is /books

def index
   @books = Book.all
end

2.2 Using Render
2.2.1 Rendering Nothing
render :nothing => true
2.2.2 Rendering an Action's View
def update
  @book = Book.find(params[:id])
     if @book.update_attributes(params[:book])
        redirect_to(@book)
     else
        render "edit"
     end
  end
end

if the call to update_attributes fails, it will render the edit.html.erb template.

2.2.3 Rendering an Action's Template from Another Controller
render "products/show"
app/controllers/admin render to app/views/products

2.2.4 Rendering an Arbitrary File
The render method can also use a view that's entirely outside of your application.
render "/u/apps/warehouse_app/current/app/views/products/show"

This takes a absolute file-system path.

render :file => "/u/apps/warehouse_app/.." :layout => true

By default, the file is rendered without using the current layout. If you want Rails to put the file into the current layout, you need to
add the :layout => true option.

If you are running on Windows, you should use the :file option to render a file.

2.2.5 Wrapping it up.
2.2.6 Using render with :inline
render :inline =>
    "<% products.each do |p| %><p><%= p.name %></p><% end %>"

2.2.7 Using render with :update
render :update do |page|
    page.replace_html 'warning', "Invalid options supplied"
end

2.2.8 Rendering Text
send plain text.
render :text => "ok"

2.2.9 Rendering JSON
render :json => @product

2.2.10 Rendering XML
renderml => @product

2.2.11 Rendering Vanilla JavaScript
Rails can render vanilla JavaScript (as an alternative to using update with an .rjs file)
render :js => "alert('Hello Rails');"

This will send the supplied string to the browser with a MIME type of text/javascript.

2.2.12 Option for render
Calls to the render method generally accept four options:
* :content_type
* :layout
* :status
* :location

2.2.12.1 The :content_type Option
render :file => filename, :content_type => 'application/rss'

2.2.12.2 The :layout Option
Use the :layout option to tell Rails to use a specific file as the layout for the current action
render :layout => 'special_layout'

Tell Rails to render with no layout at all:
render :layout => false

2.2.12.3 The :status Option
Rails will generate a response with correct HTML status code(in most cases, this is 200 OK.)
render :status => 500
render :status => :forbidden

2.2.12.4 The :location Option
Use :location option to set the HTTP location header
renderml => photo, :location => photo_url(photo)

2.2.13 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 file app/views/layouts/photos.html.erb, Rails will use app/views/layouts/application.html.erb.

2.2.13.1 Specifying Layouts on a per-Controller Basis
class ProductsController < ApplicationCon
     layout "inventory"
end

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

2.2.13.2 Choosing Layouts at Runtime
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.

2.2.13.3 Conditional Layouts
class ProductsController < ApplicationController
   layout "product", :except => [:index, :rss]
end

2.2.13.4 Layout Inheritance
application_controller.rb
class ApplicationController < ActionController::Base
   layout "main"
end

posts_controller.rb
class PostsController < ApplicationController
end

special_posts_controller.rb
class SpecialPostsController < PostsController
   layout "special"
end

old_posts_controller.rb
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 general, views will be rendered in the main layout
PostsController#index will use the main layout
SpecialPostsController#index will use the special layout
OldPostsController#show will use no layout at all
OldPostsController#index will use the old layout

2.2.14 Avoiding Double Render Errors
def show
    @book = Book.find(params[:id])
    if @book.special?
        render :action => "special_show" and return
    end
    render :action => "regular_show"
end

2.3 Using redirect_to
redirect_to tells the browser to send a new request for a different URL.
redirect_to photos_path   #photos URL
redirect_to :back             #back to the page they came from.

2.3.1 Getting a Different Redirect Status Code
redirect_to photos_path, :status => 301

2.3.2 The Difference Between render and redirect_to
def index
   @books = Book.all
end
def show
   @book = Book.find_by_id(params[:id])
   if @book.nil?
      render :action => "index"
   end
end

render is not right here, the @books is nil at that time.

def index
   @books = Book.all
end

def show
   @book = Book.find_by_id(params[:id])
   if @book.nil?
      redirect_to :action => :index
   end
end

def index
   @books = Book.all
end
def show
   @book = Book.find_by_id(params[:id])
   if @book.nil?
     @books = Book.all
     render "index", :alert => "Your book was not found!"
   end
end


references:
http://guides.rubyonrails.org/layouts_and_rendering.html
http://guides.rubyonrails.org/active_record_querying.html

分享到:
评论

相关推荐

    Rails.Angular.Postgres.and.Bootstrap.2nd.Edition

    Embrace the full stack of web development, from styling with Bootstrap, building an interactive user interface with Angular 2, to storing data quickly and reliably in PostgreSQL. With this fully ...

    Deploying.Rails.with.Docker.Kubernetes.and.ECS

    Docker and Kubernetes are increasing in popularity every day, but what if you want to leverage their benefits for your Rails application? This is the book you need. Deploying Rails with Docker, ...

    Rails 4 in Action(Manning,2015)

    Now in version 4, Rails is mature and powerful, and to use it effectively you need more than a few Google searches. You'll find no substitute for the guru's-eye-view of design, testing, deployment, ...

    Ruby on Rails_ Up and Running

    RUBY的经典之作,对其在RAILS下开发写得很详细

    Bootstrap for Rails (2015)

    and Images in a Rails Application 55 Setting up 56 Styling typography 57 Aligning text 61 Text transformation 62 Blockquotes 62 Styling listing elements 64 Creating and styling buttons 67 Which ...

    Agile Web Development with Rails 4

    We still start with a step-by-step walkthrough of building a real application, and in-depth chapters look at the built-in Rails features. This edition now gives new Ruby and Rails users more ...

    Rails 3 in Action

    Rails 3 in Action 2011年9月新鲜出炉,针对最新的Rails 3.1进行说明

    Rails 4 in Action, Second Edition.pdf

    Rails 4 in Action, Second Edition.pdf

    [Rails] Crafting Rails Applications (英文版)

    This pioneering book is the first resource that deep dives into the new Rails 3 APIs and shows you how use them to write better web applications and make your day-to-day work with Rails more ...

    Rails 4 in Action

    唔,1分应该还是有人下的吧,共同学习进步,Ruby on Rails is an open source web framework.... "Rails 4 in Action" is a fully-revised second edition of "Rails 3 in Action." This hands-on, compreh...

    The Rails3 Way, 2nd Edition

    He presents advanced Rails programming techniques that have been proven effective in day-to-day usage on dozens of production Rails systems and offers important insights into behavior-driven ...

    Ruby on Rails

    Rails 4 introduces a number of user-facing changes, and the ebook has been updated to match all the latest changes and new best practices in Rails. This includes full support for Ruby 2.0, controller ...

    Rails for .NET Developers

    source projects, Rails has been most easily adopted by individuals and organizations already immersed in the open source community. That means, as a Microsoft developer, you face unique challenges ...

    ruby.on.rails.up.and.running

    ruby.on.rails.up.and.running

    Beginning Ruby on Rails

    You will find a thorough introduction to both Ruby and Rails in this book. You'll get the easy instructions for acquiring and installing both; understand the nature of conditionals, loops, methods, ...

    Rails, Angular, Postgres, and Bootstrap(2nd)

    Rails, Angular, Postgres, and Bootstrap(2nd),电子书实战版

    The Rails 3 Way(2nd)

    The Rails™ 3 Way is a comprehensive resource that digs into the new features in Rails 3 and perhaps more importantly, the rationale behind them. —Yehuda Katz, Rails Core The Bible for Ruby on ...

Global site tag (gtag.js) - Google Analytics