`
sillycat
  • 浏览: 2542453 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Rails Study(10)Action Controller Overview - sessions

阅读更多
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
分享到:
评论

相关推荐

    rails-ftw-v0.18-2.1.5-4.1.8

    rails-ftw-v0.18-2.1.5-4.1.8.exe用于在windows环境下搭建readmine环境

    rails-hackernews-reddit-producthunt-clone, 黑客 news/reddit/social 链接分享网站 用 Rails 构建.zip

    rails-hackernews-reddit-producthunt-clone, 黑客 news/reddit/social 链接分享网站 用 Rails 构建 Rails 上的 Reddit-Hackernews-ProductHunt克隆演示 这是一个 readme.md的Ruby on Rails 应用程序,模仿了 Hacker...

    (Unity源码)街机外星风格射击游戏源码On Rails Shooter Template 1.20.rar

    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-2-0-2

    rails-documentation-1-2-1.zip

    标题 "rails-documentation-1-2-1.zip" 暗示这是一份关于 Ruby on Rails 框架的文档,版本为 1.2.1。Ruby 是一种面向对象的编程语言,而 Rails 是一个基于 Ruby 的开源 Web 应用程序框架,遵循 Model-View-...

    rails-chm-2-0-2.rar

    `rails-documentation-2-0-2.chm` 文件详细涵盖了这些概念,包含了关于Rails 2.0.2的API参考、教程和指南。通过仔细阅读和实践,开发者能够深入理解Rails的工作原理,并有效地开发出高效、可维护的Web应用。

    rails-documentation-1-2-0-rc1.chm

    rails-documentation-1-2-0-rc1.chm

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

    rails-controller-testing:将`assigns`和`assert_template`带回到您的Rails测试中

    gem 'rails-controller-testing' 然后执行: $ bundle 或将其自己安装为: $ gem install rails-controller-testing 规范 参见 。 从3.5.0版开始,rspec-rails会自动与该gem集成。 将gem添加到您的Gemfile就足够...

    Rails 3 in Action

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

    flexigrid+rails 新手代码-。-

    - 它包含了一系列内置的库和服务,如 Active Record(数据库操作)、Action Controller(路由和控制器)和 Action View(视图渲染)。 - Rails 提供了 RESTful 路由,使得构建 Web 服务更加简洁和直观。 - 使用 ...

    rails-beginner-s-guide

    路由系统与Rails的Action Controller紧密相连,Action Controller是Rails中负责处理HTTP请求并返回响应的MVC架构中的控制器部分。Action Controller提供了一组丰富的工具来帮助开发者构建强大的Web应用。例如,Rails...

    jquery-ui+jquery-ui-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

    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。它用于...

    sclo-ror42-rubygem-rails-html-sanitizer-1.0.3-1.el7.noarch.rpm

    官方离线安装包,测试可用。使用rpm -ivh [rpm完整包名] 进行安装

    Ruby on Rails入门经典代码

    Ruby on Rails,简称Rails,是基于Ruby语言的一个开源Web应用程序框架,它遵循MVC(Model-View-Controller)架构模式,旨在使Web开发过程更加高效、简洁。本压缩包中的"Ruby on Rails入门经典代码"提供了新手学习...

    rails-react-components-源码.rar

    本文将深入探讨"rails-react-components-源码.rar"中的关键知识点,帮助开发者理解如何在Rails应用中集成React组件。 1. **React组件化开发** React的核心概念是组件,它允许我们将UI拆分为独立、可重用的部分。在...

    rails-on-docker:在课程中创建的Rails应用程序的源代码-https-docker source code

    了解如何使用docker / docker compose创建和运行Rails应用程序。 经过测试 Mac OSX-10.10.5 码头工人-1.12.1 Docker撰写-1.8.0 指令/命令 mkdir ~/projects/noteapp cd ~/projects/noteapp # Create Gemfile # ...

Global site tag (gtag.js) - Google Analytics