`
sillycat
  • 浏览: 2543450 次
  • 性别: 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 ...

    Rails 3 in Action

    《Rails 3 in Action》是2011年由Ryan Bigg撰写的一本关于Ruby on Rails框架的权威指南,专门针对当时最新的Rails 3.1版本进行了深入解析。这本书旨在帮助开发者充分利用Rails 3.1的强大功能,提升Web应用开发的效率...

    Rails 4 in Action, Second Edition.pdf

    ### Rails 4 in Action, 第二版:关键知识点解析 #### 一、Rails 4简介与新特性 **Rails 4 in Action, 第二版** 是一本深入介绍Ruby on Rails框架的专业书籍。该书由Ryan Bigg、Yehuda Katz、Steve Klabnik和...

    Ruby on Rails_ Up and Running

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

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

    rails2-sample

    从给定的文件信息来看,我们正在探讨的是一本关于Ruby on Rails的书籍,书名为《Simply Rails2》,作者是Patrick Lenz。本书旨在为初学者提供深入理解Ruby on Rails框架的指南,从基础概念到高级主题均有涵盖,是...

    [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...

    Rails项目源代码

    Ruby on Rails,通常简称为Rails,是一个基于Ruby编程语言的开源Web应用框架,遵循MVC(Model-View-Controller)架构模式。这个“Rails项目源代码”是一个使用Rails构建的图片分享网站的完整源代码,它揭示了如何...

    Rails101_by_rails4.0

    《Rails101_by_rails4.0》是一本专注于Rails 4.0.0版本和Ruby 2.0.0版本的自学教程书籍,它定位于中文读者,旨在成为学习Rails框架的参考教材。Rails(Ruby on Rails)是一个采用Ruby语言编写的开源Web应用框架,它...

    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.up.and.running

    《Ruby on Rails Up and Running》是一本专注于介绍Ruby on Rails框架的书籍,旨在帮助开发者快速上手并深入了解这个强大的Web开发平台。Ruby是一种面向对象的编程语言,以其简洁、优雅的语法著称,而Rails是基于...

    Rails3 device and cancan

    标题《Rails3 device and cancan》与描述《ROR ruby on rails device plugin教程》指出本文是关于如何在Rails 3.2应用程序中整合Devise认证插件和Cancan授权插件的教程。Devise是一个流行的Ruby on Rails的认证解决...

    关于rails 3.1 cucumber-rails 1.2.0

    Rails 3.1 和 Cucumber-Rails 1.2.0 是两个在Web开发领域非常重要的工具,尤其对于Ruby on Rails框架的测试和自动化流程。本文将深入探讨这两个组件,以及它们如何协同工作来增强软件开发的效率和质量。 首先,...

Global site tag (gtag.js) - Google Analytics