5.5. Controllers5.5.1. Controller MethodsEach public method in a controller is callable by the default URL scheme /controller/action ( /world/hello , in this example): class WorldController < ApplicationController def hello render :text => 'Hello world' end All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params hash: /world/hello/1?foo=bar id = params[:id] # 1 foo = params[:foo] # bar Instance variables defined in the controller's methods are available to the corresponding view templates: def show @person = Person.find( params[:id]) end Determine the type of response accepted: def index @posts = Post.find :all respond_to do type type.html # using defaults, which will render weblog/index.rhtml type.xml { render :action => "index.rxml" } type.js { render :action => "index.rjs" } end end Learn more: http://api.rubyonrails.com/classes/ActionController/Base.html. 5.5.2. RenderUsually the view template with the same name as the controller method is used to render the results. 5.5.3. Actionrender :action => 'some_action' # the default. Does not need to be specified # in a controller method called "some_action" render :action => 'another_action', :layout => false render :action => 'some_action', :layout => 'another_layout' 5.5.4. PartialsPartials are stored in files whose filename begins with an underscore (like _error , _subform , and _listitem ): render :partial => 'subform' render :partial => 'error', :status => 500 render :partial => 'subform', :locals => { :variable => @other_variable } render :partial => 'listitem', :collection => @list render :partial => 'listitem', :collection => @list, :spacer_template => 'list_divider' 5.5.5. TemplatesSimilar to rendering an action, but finds the template based on the template root ( app/views ): render :template => 'weblog/show' # renders app/views/weblog/show 5.5.6. Filesrender :file => '/path/to/some/file.rhtml' render :file => '/path/to/some/filenotfound.rhtml', status => 404, :layout => true 5.5.7. Textrender :text => "Hello World" render :text => "This is an error", :status => 500 render :text => "Let's use a layout", :layout => true render :text => 'Specific layout', :layout => 'special' 5.5.8. Inline TemplateUses ERb to render the " miniature " template: render :inline => "<%= 'hello, ' * 3 + 'again' %>" render :inline => "<%= 'hello ' + name %>", :locals => { :name => "david" } 5.5.9. RJSdef refresh render :update do page page.replace_html 'user_list', :partial => 'user', :collection => @users page.visual_effect :highlight, 'user_list' end end 5.5.10. Change content_typerender :action => "atom.rxml", :content_type => "application/atom+xml" 5.5.11. Redirectsredirect_to(:action => "edit") redirect_to(:controller => "accounts", :action => "signup") 5.5.12. Nothingrender :nothing render :nothing, :status => 403 # forbidden Learn more:
5.5.13. URL RoutingIn config/routes.rb : map.connect '', :controller => 'posts', :action => 'list' # default map.connect ':action/:controller/:id' map.connect 'tasks/:year/:month', :controller => 'tasks', :action => 'by_date', :month => nil, :year => nil, :requirements => {:year => //d{4}/, :month => //d{1,2}/ } Learn more: http://manuals.rubyonrails.com/read/chapter/65. 5.5.14. FilterFilters can change a request before or after the controller. They can, for example, be used for authentication, encryption, or compression: before_filter :login_required, :except => [ :login ] before_filter :autenticate, :only => [ :edit, :delete ] after_filter :compress It's also possible to use a proc for a really small filter action: before_filter { controller false if controller.params["stop_action"] } Change the order of your filters by using prepend_before_filter and prepend_after_filter (like prepend_before_filter :some_filter , which will put the some_filter at the beginning of the filter chain). If you define a filter in a superclass, you can skip it in the subclass: skip_before_filter :some_filter skip_after_filter :some_filter Learn more: http://api.rubyonrails.com/classes/ActionController/Filters/ClassMethods.html. 5.5.15. Session/FlashTo save data across multiple requests , you can use either the session or the flash hashes. A flash stores a value (normally text) until the next request, while a session stores data during the complete session. session[:user] = @user flash[:message] = "Data was saved successfully" <%= link_to "login", :action => 'login' unless session[:user] %> <% if flash[:message] %> <div><%= h flash[:message] %></div> <% end %> 5.5.15.1. Session managementIt's possible to turn off session management: session :off # turn session managment off session :off, :only => :action # only for this :action session :off, :except => :action # except for this action session :only => :foo, # only for :foo when doing HTTPS :session_secure => true session :off, :only => :foo, # off for foo, if uses as Web Service :if => Proc.new { req req.parameters[:ws] } Learn more at the following site: http://api.rubyonrails.com/classes/ActionController/SessionManagement/ClassMethods.html. 5.5.16. Cookies5.5.16.1. Settingcookies[:user_name] = "david" # => Will set a simple session cookie cookies[:login] = { :value => "XJ-122", :expires => Time.now + 3600} # => Will set a cookie that expires in 1 hour 5.5.16.2. Readingcookies[:user_name] # => "david" cookies.size # => 2 5.5.16.3. Deletingcookies.delete :user_name Option symbols for setting cookies:
Learn more: http://api.rubyonrails.com/classes/ActionController/Cookies.html. |