- 浏览: 2542453 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
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(10)Action Controller Overview - sessions
1. What Does a Controller Do?
Action Controller is the C in MVC.
For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output.
A controller can thus be thought of as a middle man between models and views.
2. Methods and Actions
class ClientsController < ApplicationController
def new
end
end
As an example, if a use goes to /clients/new in your application to add a new client, Rails will create an instance of ClientsController and run the new method.
3. Parameters
There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters.
The second type of parameter is usually referred to as POST data.
Rails does not make any distinction between query string parameters and POST parameters, and both are available in the params hash in your controller.
class ClientsController < ActionController::Base
def index
if params[:status] == "activated"
@clients = Client.activated
else
@clients = Client.unactivated
end
def create
@client = Client.new(params[:client])
if @client.save
redirect_to @client
else
render :action => "new"
end
end
end
3.1 Hash and Array Parameters
The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested)hashes.
To send an array of values, append an empty pair of square brackets "[]" to the key name:
GET /clients?ids[]=1&ids[]=2&ids[]=3
The actual URL in this example will be encoded as “/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=3
The value of params[:ids] in our controller will be ["1","2","3"]. All parameter values are always strings, Rails makes no attempt to guess or cast the type.
In erb files:
<form action="/clients" method="post">
<input type="text" name="client[name]" value="Acme" />
<input type="text" name="client[phone]" value="12345" />
<input type="text" name="client[address][postcode]" value="12345" />
<input type="text" name="client[address][city]" value="Carrot City" />
</form>
In rb controller:
{
"name" => “Acme”,
“phone” => “12345”,
“address” => {
"postcode" => “12345”,
“city” => “Carrot City”
}
}
3.2 Routing Parameters
3.3 default_url_options
class ApplicationController < ActionController::Base
def default_url_options(options)
{:locale => I18n.locale}
end
end
4 Session
The session is only avaiable in the controller and the view.
*CookieStore ----- Stores everything on the client
*DRbStore ----- Stores the data on a DRb server
*MemCacheStore--Stores the data in a memcache
*ActiveRecordStore -- Stores the data in a database using Active Record.
All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure)
The CookieStore can store around 4kB of data. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances)
If you need a different session storage mechanism, you can change it in the config/initializers/session_store.rb file.
We can add a domain name
Console::Application.config.session_store :cookie_store, :key => '_console_session', :domain => ".sillycat.com"
Rails sets up (for the CookieStore) a secret key used for signing the session data. This can be changed in config/initializers/secret_token.rb
4.1 Accessing the Session
Sessions are lazily loaded. If you don't accesss sessions in your action's code, they will not be loaded. Hence you will need to disable sessions, just not accessing them will do the job.
class ApplicationController < ActionController::Base
private
def current_user
@_current_user || = session[:current_user_id] &&
user.find(session[:current_user_id])
end
end
store something in the session
class LoginsController < ApplicationController
def create
if user = User.authenticate(params[:username], params[:password])
session[:current_user_id] = user.id
redirect_to root_url
end
end
end
to remove something from the session, assign that key to be nil:
class LoginsController < ApplicationController
def destroy
@_current_user = session[:current_user_id] = nil
redirect_to root url
end
end
4.2 The Flash
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc.
class LoginsController < ApplicationController
def destroy
session[:current_user_id] = nil
flash[:notice] = "you have successfully logged out!"
redirect_to root_url
end
end
Do this in another way
redirect_to root_url, :notice => "you have successfully logged out!"
In the erb files, we can do like this:
<html>
<body>
<% if flash[:notice] %>
<p class="notice"><%= flash[:notice] %></p>
<% end %>
<% if flash[:error] %>
<p class="error"><%= flash[:error] %></p>
<% end %>
</body>
</html>
To carried over to another request
class MainController < ApplicationController
def index
flash.keep
redirect_to users_url
end
end
4.2.1 flash.now
Sometimes, we just render in the same request, we can use flash.now.
class ClientsController < ApplicationControoler
def create
@client = Client.new(params[:client]
if @client.save
#...snip...
else
flash.now[:error] = "could not save client!"
render :action => "new"
end
end
end
references:
http://guides.rubyonrails.org/action_controller_overview.html
1. What Does a Controller Do?
Action Controller is the C in MVC.
For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output.
A controller can thus be thought of as a middle man between models and views.
2. Methods and Actions
class ClientsController < ApplicationController
def new
end
end
As an example, if a use goes to /clients/new in your application to add a new client, Rails will create an instance of ClientsController and run the new method.
3. Parameters
There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters.
The second type of parameter is usually referred to as POST data.
Rails does not make any distinction between query string parameters and POST parameters, and both are available in the params hash in your controller.
class ClientsController < ActionController::Base
def index
if params[:status] == "activated"
@clients = Client.activated
else
@clients = Client.unactivated
end
def create
@client = Client.new(params[:client])
if @client.save
redirect_to @client
else
render :action => "new"
end
end
end
3.1 Hash and Array Parameters
The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested)hashes.
To send an array of values, append an empty pair of square brackets "[]" to the key name:
GET /clients?ids[]=1&ids[]=2&ids[]=3
The actual URL in this example will be encoded as “/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=3
The value of params[:ids] in our controller will be ["1","2","3"]. All parameter values are always strings, Rails makes no attempt to guess or cast the type.
In erb files:
<form action="/clients" method="post">
<input type="text" name="client[name]" value="Acme" />
<input type="text" name="client[phone]" value="12345" />
<input type="text" name="client[address][postcode]" value="12345" />
<input type="text" name="client[address][city]" value="Carrot City" />
</form>
In rb controller:
{
"name" => “Acme”,
“phone” => “12345”,
“address” => {
"postcode" => “12345”,
“city” => “Carrot City”
}
}
3.2 Routing Parameters
3.3 default_url_options
class ApplicationController < ActionController::Base
def default_url_options(options)
{:locale => I18n.locale}
end
end
4 Session
The session is only avaiable in the controller and the view.
*CookieStore ----- Stores everything on the client
*DRbStore ----- Stores the data on a DRb server
*MemCacheStore--Stores the data in a memcache
*ActiveRecordStore -- Stores the data in a database using Active Record.
All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure)
The CookieStore can store around 4kB of data. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances)
If you need a different session storage mechanism, you can change it in the config/initializers/session_store.rb file.
We can add a domain name
Console::Application.config.session_store :cookie_store, :key => '_console_session', :domain => ".sillycat.com"
Rails sets up (for the CookieStore) a secret key used for signing the session data. This can be changed in config/initializers/secret_token.rb
4.1 Accessing the Session
Sessions are lazily loaded. If you don't accesss sessions in your action's code, they will not be loaded. Hence you will need to disable sessions, just not accessing them will do the job.
class ApplicationController < ActionController::Base
private
def current_user
@_current_user || = session[:current_user_id] &&
user.find(session[:current_user_id])
end
end
store something in the session
class LoginsController < ApplicationController
def create
if user = User.authenticate(params[:username], params[:password])
session[:current_user_id] = user.id
redirect_to root_url
end
end
end
to remove something from the session, assign that key to be nil:
class LoginsController < ApplicationController
def destroy
@_current_user = session[:current_user_id] = nil
redirect_to root url
end
end
4.2 The Flash
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc.
class LoginsController < ApplicationController
def destroy
session[:current_user_id] = nil
flash[:notice] = "you have successfully logged out!"
redirect_to root_url
end
end
Do this in another way
redirect_to root_url, :notice => "you have successfully logged out!"
In the erb files, we can do like this:
<html>
<body>
<% if flash[:notice] %>
<p class="notice"><%= flash[:notice] %></p>
<% end %>
<% if flash[:error] %>
<p class="error"><%= flash[:error] %></p>
<% end %>
</body>
</html>
To carried over to another request
class MainController < ApplicationController
def index
flash.keep
redirect_to users_url
end
end
4.2.1 flash.now
Sometimes, we just render in the same request, we can use flash.now.
class ClientsController < ApplicationControoler
def create
@client = Client.new(params[:client]
if @client.save
#...snip...
else
flash.now[:error] = "could not save client!"
render :action => "new"
end
end
end
references:
http://guides.rubyonrails.org/action_controller_overview.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 428Private 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 468NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 414Prometheus 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 445GraphQL 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 310Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 286Serverless 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 281NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 257Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 565NodeJS 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 365Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
rails-ftw-v0.18-2.1.5-4.1.8.exe用于在windows环境下搭建readmine环境
rails-hackernews-reddit-producthunt-clone, 黑客 news/reddit/social 链接分享网站 用 Rails 构建 Rails 上的 Reddit-Hackernews-ProductHunt克隆演示 这是一个 readme.md的Ruby on Rails 应用程序,模仿了 Hacker...
2-94街机外星风格射击游戏源码On Rails Shooter Template 1.202-94街机外星风格射击游戏源码On Rails Shooter Template 1.202-94街机外星风格射击游戏源码On Rails Shooter Template 1.202-94街机外星风格射击游戏...
rails-documentation-2-0-2
标题 "rails-documentation-1-2-1.zip" 暗示这是一份关于 Ruby on Rails 框架的文档,版本为 1.2.1。Ruby 是一种面向对象的编程语言,而 Rails 是一个基于 Ruby 的开源 Web 应用程序框架,遵循 Model-View-...
`rails-documentation-2-0-2.chm` 文件详细涵盖了这些概念,包含了关于Rails 2.0.2的API参考、教程和指南。通过仔细阅读和实践,开发者能够深入理解Rails的工作原理,并有效地开发出高效、可维护的Web应用。
rails-documentation-1-2-0-rc1.chm
### Rails 4 in Action, 第二版:关键知识点解析 #### 一、Rails 4简介与新特性 **Rails 4 in Action, 第二版** 是一本深入介绍Ruby on Rails框架的专业书籍。该书由Ryan Bigg、Yehuda Katz、Steve Klabnik和...
gem 'rails-controller-testing' 然后执行: $ bundle 或将其自己安装为: $ gem install rails-controller-testing 规范 参见 。 从3.5.0版开始,rspec-rails会自动与该gem集成。 将gem添加到您的Gemfile就足够...
《Rails 3 in Action》是2011年由Ryan Bigg撰写的一本关于Ruby on Rails框架的权威指南,专门针对当时最新的Rails 3.1版本进行了深入解析。这本书旨在帮助开发者充分利用Rails 3.1的强大功能,提升Web应用开发的效率...
- 它包含了一系列内置的库和服务,如 Active Record(数据库操作)、Action Controller(路由和控制器)和 Action View(视图渲染)。 - Rails 提供了 RESTful 路由,使得构建 Web 服务更加简洁和直观。 - 使用 ...
路由系统与Rails的Action Controller紧密相连,Action Controller是Rails中负责处理HTTP请求并返回响应的MVC架构中的控制器部分。Action Controller提供了一组丰富的工具来帮助开发者构建强大的Web应用。例如,Rails...
在这个案例中,我们看到`jquery-ui-rails-4.2.1.gem`,这是该gem的一个特定版本。这个gem负责将jQuery UI的库文件打包并整合到Rails的asset pipeline中,使得在Rails项目中使用jQuery UI变得简单。 要使用`jquery-...
Ajax-Rails-4-AJAX-modal-form-render-JS-response-as-table-row.zip,rails 4 ajax模式表单将js响应呈现为表行,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。它用于...
官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装
Ruby on Rails,简称Rails,是基于Ruby语言的一个开源Web应用程序框架,它遵循MVC(Model-View-Controller)架构模式,旨在使Web开发过程更加高效、简洁。本压缩包中的"Ruby on Rails入门经典代码"提供了新手学习...
本文将深入探讨"rails-react-components-源码.rar"中的关键知识点,帮助开发者理解如何在Rails应用中集成React组件。 1. **React组件化开发** React的核心概念是组件,它允许我们将UI拆分为独立、可重用的部分。在...
了解如何使用docker / docker compose创建和运行Rails应用程序。 经过测试 Mac OSX-10.10.5 码头工人-1.12.1 Docker撰写-1.8.0 指令/命令 mkdir ~/projects/noteapp cd ~/projects/noteapp # Create Gemfile # ...