- 浏览: 2543450 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
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
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
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 468NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 330Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 430Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 377Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 469NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 415Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 332Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 243GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 446GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 321GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 307Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 313Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 288Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 303Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 282NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 258Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 566NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 257Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 362Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 366Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
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》是2011年由Ryan Bigg撰写的一本关于Ruby on Rails框架的权威指南,专门针对当时最新的Rails 3.1版本进行了深入解析。这本书旨在帮助开发者充分利用Rails 3.1的强大功能,提升Web应用开发的效率...
### Rails 4 in Action, 第二版:关键知识点解析 #### 一、Rails 4简介与新特性 **Rails 4 in Action, 第二版** 是一本深入介绍Ruby on Rails框架的专业书籍。该书由Ryan Bigg、Yehuda Katz、Steve Klabnik和...
RUBY的经典之作,对其在RAILS下开发写得很详细
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 ...
从给定的文件信息来看,我们正在探讨的是一本关于Ruby on Rails的书籍,书名为《Simply Rails2》,作者是Patrick Lenz。本书旨在为初学者提供深入理解Ruby on Rails框架的指南,从基础概念到高级主题均有涵盖,是...
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 ...
唔,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...
Ruby on Rails,通常简称为Rails,是一个基于Ruby编程语言的开源Web应用框架,遵循MVC(Model-View-Controller)架构模式。这个“Rails项目源代码”是一个使用Rails构建的图片分享网站的完整源代码,它揭示了如何...
《Rails101_by_rails4.0》是一本专注于Rails 4.0.0版本和Ruby 2.0.0版本的自学教程书籍,它定位于中文读者,旨在成为学习Rails框架的参考教材。Rails(Ruby on Rails)是一个采用Ruby语言编写的开源Web应用框架,它...
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框架的书籍,旨在帮助开发者快速上手并深入了解这个强大的Web开发平台。Ruby是一种面向对象的编程语言,以其简洁、优雅的语法著称,而Rails是基于...
标题《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 是两个在Web开发领域非常重要的工具,尤其对于Ruby on Rails框架的测试和自动化流程。本文将深入探讨这两个组件,以及它们如何协同工作来增强软件开发的效率和质量。 首先,...