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

你可能感兴趣的:(mvc,action,Rails)