- 浏览: 2492148 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
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 435NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 297Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 380Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 342Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 424NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 369Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 297Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 214GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 398GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 283GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 273Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 268Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 256Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 244Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 240NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 229Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 527NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 232Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 325Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 324Supervisor 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 4 in Action is a hands-on guide to the subject. In this fully revised new edition, you'll master Rails 4 by developing a ticket-tracking application that includes RESTful routing, authentication...
rails-angular-postgres-and-bootstrap-second-edition 英文原版
rails-documentation-2-0-2
rails-documentation-1-2-1.zip
rails-documentation-1-2-0-rc1.chm
gem 'rails-controller-testing' 然后执行: $ bundle 或将其自己安装为: $ gem install rails-controller-testing 规范 参见 。 从3.5.0版开始,rspec-rails会自动与该gem集成。 将gem添加到您的Gemfile就足够...
jquery-ui+jquery-ui-rails
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。它用于...
rails-beginner-s-guide是Rails 指导手册,帮组学习了解rails开发
官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装
rails-react-components-源码.rar
rails-yelp-mvp-源码.rar
rails-builds-test-源码.rar
rails-development-environment-master.rar
了解如何使用docker / docker compose创建和运行Rails应用程序。 经过测试 Mac OSX-10.10.5 码头工人-1.12.1 Docker撰写-1.8.0 指令/命令 mkdir ~/projects/noteapp cd ~/projects/noteapp # Create Gemfile # ...
会话控制器实验室 ... 注意:如果使用生成器生成控制器,请确保传递这些标志,以避免生成不需要的文件: rails generate controller Sessions new --no-helper --no-assets --no-controller-specs 。 编
Ruby on Rails与MongoDB 您可以在MongoDB的帮助下轻松... rails new ruby-on-rails-with-mongodb --skip-active-record从您的Gemfile中删除sqlite3(如果存在),将Mongoid添加到您的Gemfile中,然后运行“ bundle”。