Rails 3 Controller: Difference between revisions

From Wiki
Jump to navigation Jump to search
Line 1: Line 1:
== Routes ==
== Routes ==
defined in <code>config/routes.rb</code>:
defined in <code>config/routes.rb</code>:
<pre>
<source lang="ruby">
match ':controller(/:action(/:id(.:format)))'  # default route, :id and :format may be accessed as parameters in the action
match ':controller(/:action(/:id(.:format)))'  # default route, :id and :format may be accessed as parameters in the action
match '/teams/home' => 'teams#index'          # call index action of teams controller
match '/teams/home' => 'teams#index'          # call index action of teams controller
match '/teams/search/:query' => 'teams#search' # sends :query parameter to search action in teams controller
match '/teams/search/:query' => 'teams#search' # sends :query parameter to search action in teams controller
match '/teams/search/:query' => 'teams#search', :as => 'search'  # named route, defines search_url and search_path methods
match '/teams/search/:query' => 'teams#search', :as => 'search'  # named route, defines search_url and search_path methods
</pre>
</source>
<pre>
<pre>
search_url  => http://example.com/teams/search
search_url  => http://example.com/teams/search
Line 14: Line 14:
<source lang="ruby">
<source lang="ruby">
link_to "Search", search_path
link_to "Search", search_path
</source>
=== root url ===
use something like this in <code>config/routes.rb</code>:
<source lang="ruby">
root :to => "articles#index"
</source>
</source>



Revision as of 22:10, 30 June 2011

Routes

defined in config/routes.rb:

match ':controller(/:action(/:id(.:format)))'  # default route, :id and :format may be accessed as parameters in the action
match '/teams/home' => 'teams#index'           # call index action of teams controller
match '/teams/search/:query' => 'teams#search' # sends :query parameter to search action in teams controller
match '/teams/search/:query' => 'teams#search', :as => 'search'  # named route, defines search_url and search_path methods
search_url  => http://example.com/teams/search
search_path => /teams/search

useful in something like

link_to "Search", search_path

root url

use something like this in config/routes.rb:

root :to => "articles#index"

RESTful Routes and Resources

If you add

resources :articles

to config/routes.rb, the following named routes are automatically created:

article_path => /articles/:id  
articles_path => /articles  
edit_article_path => /articles/edit/:id  
new_article_path => /articles/new