Rails notes active controller

Source: Internet
Author: User
ArticleDirectory
    • Active Controller
    • Name routes map. xxx
    • Action Method
    • Controller environment object
    • Response Processing
    • Redirect
    • Cookies
    • Session
    • Flash
    • Filter
    • Verification
Active Controller

Model command load model object model: product in advance

Basic correspondence

The http://xxx.com/admin/hello/list corresponds to the List Method in APP/controllers/admin/hello_controller.rb as follows module admin class Hello def list end

Ctroller is created every time

Automatic URL ing map. Connect

You can define the relationship between the underlying URL and action in config/routes. RB, which makes the URL ing of rails abnormal and flexible,

The default ing is as follows: map. Connect ': Controller/: Action/: id', which automatically matches three URL requests. The detailed rules are as follows:

    • The URL is segmented into components according to the prefix "/".
    • ": Name" creates a parameter named name and assigns the corresponding URL segment to it.
    • "Name "matches all the remaining URL segments, and an array named name is created ,"Name "can only appear at the end
    • Other characters that appear in text are strictly matched.

Parameters accepted by map. Connect are as follows:

    • : Defaults = >{: name => 'value',...} sets the default value of the URL segment of the corresponding name, for example: Action => 'index'
    • : Requirements = >{: name =>/Regexp/,...} requires that the URL segment of the corresponding name must match the Regular Expression
    • : Name => value is also the default value, but the corresponding name can be retrieved by itself, not necessarily in URL matching, equivalent to the append Parameter
    • : Name =>/Regexp/has the same functions as: requirements.
URL automatically generates url_for

Corresponds to automatic URL ing. rails can use map. the information stored in connect is used to automatically construct the URL and implement friendly URL functions. For example, in the default setting, url_for: controller => "XX",: Action => "FDA ",: id => "fdas" can construct these three special URL segments

Url_for will fill in the default value based on the input URL, for example, url_for (: Action => "FDA") will default: controller is the current, assuming the URL segment is the structure of the Directory, the default values of url_for work as follows:If the sub-directory changes, its parent directory will be filled with the default value, but its sub-directory will be discarded.The change here is a change in the value, and explicitly assigning the same value does not change.

If you want to block the url_for smart default value, you can explicitly assign the highest level directory to nil, so that the default values from the highest to the lowest are discarded.

If you change the advanced level, you can use url_for (: overwrite_params => {: xxx => YYY}) to do it. In this way, rails will think that it has not changed, all low-level directory segments will be filled in

Extended parameters of url_for

    • : Anchor specifies anchor (on-page join). rails will automatically add#
    • : Host specifies the host (port can be included)
    • : Only_path only generates path, host, port, and protocol.
    • : Protocol protocol name, for example, "https ://"
    • : Add "/" to the end of trailing_slash "/",Note:The page cache system is messy when there is a report saying "/" at the end
To_param

The to_param object is implemented. When url_for is passed in, the to_param value is automatically extracted. Otherwise, the to_s object is extracted. The to_param object of the rails model automatically obtains the ID.

Name routes map. xxx

Map. xxx can be used to create a XXX route instead of map. Connect. This route also corresponds to a xxx_url method, which is the same as url_for, but the rule is only for the current route

Action Method

Rails will automatically forward the URL request to the corresponding controller class method. This method is called the action method. If the action method is not found, it will call method_missing to pass in the action name and empty parameter list, if no action method is called, rails directly jumps to the template corresponding to the action to implement a pure view. If no action is found, the error "unknown action" is returned.

Hiding method: private orHide_actionYesNote:If you useHide_actionYou can use the helpers class to publish private methods to other classes,Hide_actionFor the best strategy

Controller environment object
    • Request

      • Domain () Host Name
      • Remote_ip () remote IP
      • Parameters passed by the Env Browser
      • Method HTTP Request Method: delete,: Get,: Head,: Post,: Put
      • Delete ?, Get ?, Head ?, Post ?, Put? Returns true or false.
    • Params is equivalent to JSP. parametermap, similar to hash. Params [: XXX] is equivalent to Params ['xxx']. We recommend the former.

    • Cookies are similar to Params.
    • Response generally does not need it. It may be used in the filter.
    • Session
    • Headers output to the browser Header
    • There is also a logger object
Response Processing

Three Processing Methods 1. Use the view template to Output 2. directly render Text 3. Output other data (PDF, file)

Response can only be render once. Render will generate a doublerendererrorNote:Erase_render_results can be used to clear the previous render, but this method has no guarantee (unclassified ented method)

Rails checks the render. If no render is available after the controller is executed, the corresponding view will be called. If the render is executed, the view will not be dropped.

View output

The template has. Rhtml and. Rxml (builder), which is in APP/views/control/* by default. The default location is APP/views/which can be updated through actioncontroller: Base. templdate_root = xxx.

Direct render text
    • Render (: text => string) directly render the text
    • Render (: inline => string, [: TYPE => "rhtml" | "rxml"]) treats the input string as a template, which is equivalent to the rhtml content.
    • Render (: Action => action_name) directly calls an action template, which is equivalent to forward to a view.
    • Render (: file => path; [: use_full_path => true | false]) Use a template file render. When use_full_path is opened, you can enter a relative path.
    • Render (: template => name) uses the Template Name render. For example, render (: template => "blog/short_list ") # automatic use of/APP/views/blog/short_list.rhtml (rxml)
    • Render (: Partial => name )???
    • Render (: Nothing => true) does not output anything, including Layout
    • Render () default render, equivalent to render (: Action => Self)

All render receive two additional parameters: Status and layout. If layout is set to false, layout is not used. If both nil and true indicate that layout is set to string, layout using the name represented by string

Use render_to_string (the same usage as render) to get the output string instead of directly outputting it to the browser.

Output other data

Send_data (data, options...) supports the following options:

    • : Filename: Recommended file name for the browser
    • : Type file type. The default value is "application/octet-stream"
    • : Disposition indicates the browser's processing suggestion. "inline" indicates direct display, and "attachment" indicates downloading another storage.

Like send_file and send_data, send_file has one more parameter: streaming. When stream is set to false, the entire file is read into the memory for transmission. Otherwise, the stream is transmitted using buffer_size.

Redirect
    • Redirect_to (: Action => 'xxx') uses the same syntax as url_for (url_for at the underlying layer)
    • Redirect_to ("/localpath ")
    • Redirect_to ("http: // URL ")

The default redirect is tempoary.

Cookies

Cookies must use string values. If other values are used, errors such as "Private method 'gsub' called" may occur.

Example of cookie extension parameters:

Cookies [: marsupial] = {: value => "wombat",: expires => 30. Days. from_now,: Path => "/Store "}

    • : Direct value of Value
    • : Domain storage and access address
    • : Expires expiration time
    • : Path and domain jointly determine the storage and access address
    • : Whether secure is only used in https //
Session

Sessions are stored as files by default. You can delete them to update the class structure conflict (the old object and the new object are different)

Specific session configurations can be configured in config/environments (except for session expiration time)

Example:

 
Actioncontroller: cgirequest: default_session_options [: session_key] = 'my _ app'
  • : Database_manager controls how the session data is stored on the server. We'll have more to say about this shortly.
  • : Session_domain the domain of the cookie used to store the session ID on the browser. defaults to the application's host name.
  • : Session_id overrides the default session ID. If not set, new sessions automatically have a 32-character key created for them. This key is used in subsequent requests.
  • : Session_key the name of the cookie used to store the session ID. You'll want to override this in your application, as shown previusly.
  • : Session_path the Request Path to which this session applies (it's actually the path of the cookie). The default is/, so it applies to all applications in this domain.
  • : Session_secure if true, sessions will be enabled only over https: //. The default is false.
  • : New_session directly maps to the underlying Cookie's new_session option. however, this option is unlikely to work the way you need it to under rails, and we'll discuss an alternative in section 16.8, time-based expiry of cached pages, on page 323.
  • : Session_expires the absolute time of the expiry of this session. Like: new_session, this option shoshould probably not be used under rails.

For more settings, refer to the CGI: session document.

Default_session_options also has a database_manager storage method that can be configured for sessions (: database_manager => XXXX). The list is as follows:

    • CGI: Session: pstore default storage method, using marshal
    • CGI: Session: activerecordstore uses activerecord to store the create table sessions (ID int (11) not null auto_increment, sessid varchar (255), Data Text, updated_at datetime default null, primary Key (ID), index session_index (sessid ));
    • CGI: Session: drbstore is accessed by using drbserver. It comes with a drb_server.rb
    • CGI: Session: memcachestore uses the cache system ???
    • CGI: Session: memorystore Direct Memory storage, not recommended
    • CGI: Session: filestore direct file storage, not recommended, only supports string Storage

Set: actioncontroller: cgirequest: default_session_options = false to disable all sessions and the function of relying on sessions (flash)

Session Storage Method Comparison

View here http://media.pragprog.com/ror/sessions/, one sentence first with the simplest direct, wait until the speed slows down when the certification measurement, and then make a decision, do not overkill

Session clearing

Rails is relatively primitive at present. You have to clear it yourself. Write crontab (clear file, clear table )???

Flash

The life cycle of Flash is two requests, and the underlying uses session to save the object flash. now create a temporary flash (within a request. now [: XXX] Flash. keep delays the lifetime flash of a request. keep (: XXX) or flash. keep (all)

Filter

Before_filter after_filter around_filter

The filter parameter can be set as a method Symbol: method_a, a block or a class, and the static method self of this class. filter () is called. The default filter acts on all action methods of the current class and the Action methods of the subclass. The: only and: distinct T are used to include or exclude actions in the controller.

Before_filter and after_filter are added to filter chains by default. If you want to add them to the beginning, use prepend_before_filter () and prepend_after_filter ()

Before_filter is mainly used to verify after_filter. It is mainly used to control the content (compression, replacement). around_filter can be used to record the time. The parameter must be a class, which has two methods: Before (Controller) and after (Controller ).Around_filter xxxfilter. New

Around_filter is nested, and around_filter. new, B. the result of new is as follows:. before B. before action ..... b. after. note that the order of after is different from that of the first two filters.

Relationship between filters in inheritance

The sub-controller executes all filters of the parent controller, but the parent does not execute the sub-filter.

Verification

The Verify command can be seen as a specially extracted filter function. When verify fails, the current action will not execute class blogcontroller <applicationcontroller verify: Only =>: post_comment,: Session =>: user_id,: add_flash =>{: note => "you must log in to comment"},: redirect_to =>: index #.... the following conditions are supported by end: Only =>: Name or [: name,...]: Counter T => name or [: name,...] test Conditions: Flash =>: Key or [: Key,...] flash must contain some keys: method =>: symbol or [: symbol,...] the request must be a certain HTTP Method: Session =>: Key or [: Key,...] the session must contain some keys for the operation: add_flash => hash to write the hash value pair into FLASH: redirect_to => Params jump to the page

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.