- 浏览: 2502341 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
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 446NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 303Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 390Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 351Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 435NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 382Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 310Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 222GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 409GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 288GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 284Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 279Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 263Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 252Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 251NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 238Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 535NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 238Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 334Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 335Supervisor 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 ...
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, ...
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的经典之作,对其在RAILS下开发写得很详细
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 ...
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 2011年9月新鲜出炉,针对最新的Rails 3.1进行说明
Rails 4 in Action, Second Edition.pdf
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...
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 ...
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 ...
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
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),电子书实战版
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 ...