Routing Flashcards
How to add ‘/hello’ get action?(7 ways)
get ‘application/hello’
get ‘hello’, to: ‘application#hello’
get ‘hello’ => ‘application#hello’
get ‘hello’, controller: ‘application’, action: ‘hello’
# ———————– with match —————-
match ‘hello’ => ‘application#hello’, via: :get
match ‘hello’, to: ‘application#hello’, via: :get
match ‘hello’, controller: ‘application’, action: ‘hello’, via: :get
How to add dynamic params to route?
get 'hello/:id', controller: 'application', action: 'hello' # params[:id]
How to send default segment params( keys)?
get 'hello/:id', to: 'application#hello', defaults: {something: 'hi'} # params[:something]
How to redirect?
get ‘hello’, to: redirect(‘/’)
How to add segment key for format to the request?
get 'hello/:id(.:format)', to: 'application#hello' # params[:format]
How to route action without a controller?
get 'hello', to: proc { |env| [200, {}, ["Hello world"]] } # => 'Hello world'
How to set constraints for segment key?(2 ways)
get ‘hello/:id’, to: ‘application#hello’, constraints: { id: /\d+/}
get ‘hello/:id’, to: ‘application#hello’, id: /\d+/
How to add root action? (2 ways)
root to: ‘application#hello’
root ‘application#hello’
How to add globbing values to the route?
get 'hello/*something' => 'application#hello' # params[something] #=> one/two/some
How to add a custom name for path?
get 'hello' => 'application#hello', as: :my_hello # my_hello_path
What is the difference between name_path and name_url?
The difference is that the _url method generates an entire URL, including protocol and domain, whereas the _path method generates just the path part (sometimes referred to as an absolute path or a relative URL).
How to create a scope?
scope ‘sample’ do
get ‘hello’ => ‘application#hello’
end
# sample/hello
How to use a common controller in a scope? ( 2 way )
scope 'sample', controller: 'application' do get 'hello', action: :hello end # sample/hello # ---------------- controller 'application' do get 'hello', action: :hello end
How to add namespace?
namespace :application do
get ‘hello’, action: :hello
end
How to add direct url?
direct(:apple) { "http://www.apple.com" } # apple_url #=> http://www.apple.com