-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrails_routes_notes.txt
592 lines (398 loc) · 22.9 KB
/
rails_routes_notes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
Rails Routes
==========================================================================================
- https://guides.rubyonrails.org/routing.html
- Create a route that maps a URL to the controller action
Rails.application.routes.draw do
get 'homepage/index'
root 'homepage#index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
- mounted on '/' .. the root
--> app/controllers/homepage_controller.index --> app/views/homepage/index.html.erb
- Shorthand for connecting a route to a controller/action
config/routes.rb:
get 'welcome' => 'pages#home'
get 'photos/show'
# The above is the same as:
get 'photos/show', :to 'photos#show'
get 'photos/show' => 'photos#show'
- Automagically create all the routes for a RESTful resource
config/routes.rb:
resources :photos -->
HTTP Verb Path Controller#Action Used for
GET /photos photos#index display a list of all photos
GET /photos/new photos#new return an HTML form for creating a new photo
POST /photos photos#create create a new photo
GET /photos/:id photos#show display a specific photo
GET /photos/:id/edit photos#edit return an HTML form for editing a photo
PATCH/PUT /photos/:id photos#update update a specific photo
DELETE /photos/:id photos#destroy delete a specific photo
- Create resources for only certain actions
config/routes.rb:
resources :photos, :only => [:index]
# On the flip side, you can create a resource with exceptions
resources :photos, :except => [:new, :create, :edit, :update, :show, :destroy]
- Create a route to a static view, without an action in the controller
config/routes.rb:
# If there's a file called 'about.html.erb' in 'app/views/photos', this file will be
# automatically rendered when you call localhost:3000/photos/about
get 'photos/about', to: 'photos#about'
articles GET /articles(.:format) {action:"index", controller:"articles"}
- Also, you can for one action :
resources :home, only: [:index]
- What is on: :collection or on: :member
resources :posts do
# on collection
get 'search', on: :collection
# --> generates '/posts/search' and search_posts_path
# on member
get 'share', on: :member
# --> generates'/posts/:id/share' and share_post_path(@post)
end
- Notice, to add new route to extsing resource ..
get 'books/react', :to => 'books/react' <------ this
resources :books do
# get 'react', on: :collection <----- or this
end
TestApp::Application.routes.draw do
resources :courses do
member do <---- or like this
get "preview" # Preview a single course (requires ID)
end
collection do <---- or like this
get "upcoming" # Show a list of *all* upcoming courses (no ID needed)
end
end
end
- Using redirects
- Normal usage
TestApp::Application.routes.draw do
get 'courses/:course_name' => redirect('/courses/%{course_name}/lessons'), :as => "course"
match "/posts/:id" => redirect("/articles/%{id}")
end
- fetch params and req
get '/stories/:name', to: redirect { |path_params, req| "/articles/#{path_params[:name].pluralize}" }
get '/stories', to: redirect { |path_params, req| "/articles/#{req.subdomain}" }
- status
get '/stories/:name', to: redirect('/articles/%{name}', status: 302)
- Handling Parameters and Formats
The only other complex part about a table entry is the path. Here are the unique path patterns from the above table:
/articles(.:format)
/articles/new(.:format)
/articles/:id/edit(.:format)
/articles/:id(.:format)
- Nested Resources
- Nested resources sound like a great idea because they can build up beautiful URLs. For instance, let’s say our articles are going to have comments. For an article with ID 16 we might want to list the comments with this URL:
http://localhost:3000/articles/16/comments
- To create this, we nest the comments resource inside the articles like below:
MyApp::Application.routes.draw do
resources :articles do
member do
put 'publish'
end
collection do
put 'publish_all'
end
resources :comments
end
end
# Remember, if you want to create a resources to a controller "messages" for example
resources :messages
This will generate of course:
messages GET /messages(.:format) messages#index
POST /messages(.:format) messages#create
new_message GET /messages/new(.:format) messages#new
edit_message GET /messages/:id/edit(.:format) messages#edit
message GET /messages/:id(.:format) messages#show
PATCH /messages/:id(.:format) messages#update
PUT /messages/:id(.:format) messages#update
DELETE /messages/:id(.:format) messages#destroy
- Let's add some nested (addition routes to our messages route)
resources :messages
resources :users do
resources :messages
end
# this will add
# remember, you can always use only [:edit, create ... ] to specify which actions to incluide in which scope
# resources :messages, :only => [:create, :index, :new]
.....
user_messages GET /users/:user_id/messages(.:format) messages#index
POST /users/:user_id/messages(.:format) messages#create
new_user_message GET /users/:user_id/messages/new(.:format) messages#new
edit_user_message GET /users/:user_id/messages/:id/edit(.:format) messages#edit
user_message GET /users/:user_id/messages/:id(.:format) messages#show
PATCH /users/:user_id/messages/:id(.:format) messages#update
PUT /users/:user_id/messages/:id(.:format) messages#update
DELETE /users/:user_id/messages/:id(.:format) messages#destroy
.....
- This shall reflect the following on models, controllers and forms ...
get /users/2/messages --> retreive all messages belongs to user [2] via path: user_messages_path
- via helpers
<%= user_messages_path(2) %> --> /users/2/messages
<%= user_messages_url(2) %> --> http://legion.com:3000/users/3/messages # the domain came from development.rb: config.hosts << "legion.com"
<%= user_message_path(2,4) %> --> /users/2/messages/4
# you can pass resources
<%= user_message_path(@user,comment) %>
- via forms
<%= form_for [@user, @comment] do |f| %>
- delete link for example
For example, inside a collections partial with comment_item supplied for iteration,
<%= link_to "delete", user_comment_path(@user, comment_item), :method => :delete, :confirm => "Really?" %>
- Their unit-tests will generally get/post to the simplest:
# POST /messages
post :create, :message => {:user_id=>42, ...}
In order to test the route that they may prefer, they need to do it this way:
# POST /articles/42/comments
post :create, :user_id => 42, :message => {...}
- specify a controller for a resource
resources :photos, controller: 'images'
- resources :photos, only: [:index, :show]
- resources :photos, except: :destroy
- Non-RESTful Routes
Using a non-RESTful approach is not recommended, but you can do it if the need arises.
In routes.rb you’d call the match method and define a pattern like this:
MyApp::Application.routes.draw do
match 'articles/:id' => 'articles#show'
end
Or, to go all in, you can use the this pattern:
# not recommended
match ':controller(/:action(/:id(.:format)))'
- to define a route name, for certain controller, action and for certain methods
match 'photos', to: 'photos#show', via: [:get, :post] # get, post, put, patch, delete
# all methods
match 'photos', to: 'photos#show', via: :all
- Segment Constraint
- to accept only paths /photos/A12345, or
get 'photos/:id', to: 'photos#show', constraints: { id: /[A-Z]\d{5}/ }
get '/:id', to: 'articles#show', constraints: { id: /\d.+/ }
# only from subdomain admin
get 'photos', to: 'photos#index', constraints: { subdomain: 'admin' }
- similar to this
namespace :admin do
constraints subdomain: 'admin' do
resources :photos
end
end
- something more advanced
class RestrictedListConstraint
def initialize
@ips = RestrictedList.retrieve_ips
end
def matches?(request)
@ips.include?(request.remote_ip)
end
end
Rails.application.routes.draw do
get '*path', to: 'restricted_list#index',
constraints: RestrictedListConstraint.new
end
- same using lambda
Rails.application.routes.draw do
get '*path', to: 'restricted_list#index',
constraints: lambda { |request| RestrictedList.retrieve_ips.include?(request.remote_ip) }
end
# https://guides.rubyonrails.org/routing.html
- Type-able URLs
When an app supports authentication, you might add routes like this:
MyApp::Application.routes.draw do
resources :sessions
match '/login' => 'sessions#new', as: 'login'
match '/logout' => 'sessions#destroy', as: 'logout'
end
There are still the normal RESTful routes for sessions, but now there are the additional convenience routes /login and /logout. In addition, the :as parameter gives them a name to use with the helper. In your app you can now refer to login_path and logout_path in addition to new_session_path. Run rake routes and it’d show these:
login /login(.:format) {controller:"sessions", action:"new"}
logout /logout(.:format) {controller:"sessions", action:"destroy"}
- wildcards
get 'messages/*other', to: 'messages#index'
- this will go alywas to messages#index
- anything comes after /messages is accepted
/messages/a/b/4533 --> messages#index # controller_name and action_name will remain messages, index
# params
<%= params %> {"controller"=>"messages", "action"=>"index", "other"=>"a/b/45"}
# accepts /books/any/thing/some
- get 'books/*section/:title', to: 'books#show'
GET /messages/*other(.:format) messages#index
GET /messages/*other/:title(.:format) messages#index
- ordering is very important .. for example
get 'messages/*other', to: 'messages#index' <-- wil apply thin first
get 'messages/*some/:title', to: 'messages#index'
# /messages/a/b/45
<%= params %> -> {"controller"=>"messages", "action"=>"index", "other"=>"a/b/45"}
get 'messages/*some/:title', to: 'messages#index'
get 'messages/*other', to: 'messages#index' <-- wil apply thin first
# /messages/a/b/45
<%= params %> -> {"controller"=>"messages", "action"=>"index", "some"=>"a/b", "title"=>"45"}
# /messages/45
<%= params %> -> {"controller"=>"messages", "action"=>"index", "some"=>"a/b", "title"=>"45"}
- how to capture for example any page, without no format (.json)
get '*pages', to: 'pages#show', format: false
GET /*pages messages#index
/messages -> {"controller"=>"messages", "action"=>"index", "pages"=>"messages"}
/messages/45 -> {"controller"=>"messages", "action"=>"index", "pages"=>"messages/45"}
- singular resource (no ID)
get 'profile', to: 'users#show'
get 'profile', action: :show, controller: 'users'
- This resourceful route:
resource :geocoder
resolve('Geocoder') { [:geocoder] }
GET /geocoder/new geocoders#new return an HTML form for creating the geocoder
POST /geocoder geocoders#create create the new geocoder
GET /geocoder geocoders#show display the one and only geocoder resource
GET /geocoder/edit geocoders#edit return an HTML form for editing the geocoder
PATCH/PUT /geocoder geocoders#update update the one and only geocoder resource
DELETE /geocoder geocoders#destroy delete the geocoder resource
- namespace vs scope
# namespace
############
namespace :admin do
resources :messages
end
# admin will be added as prefix
# paths will change accordingly
# %= admin_messages_path %> --> /admin/messages
admin_messages GET /admin/messages(.:format) admin/messages#index
POST /admin/messages(.:format) admin/messages#create
new_admin_message GET /admin/messages/new(.:format) admin/messages#new
edit_admin_message GET /admin/messages/:id/edit(.:format) admin/messages#edit
admin_message GET /admin/messages/:id(.:format) admin/messages#show
PATCH /admin/messages/:id(.:format) admin/messages#update
PUT /admin/messages/:id(.:format) admin/messages#update
DELETE /admin/messages/:id(.:format) admin/messages#destroy
# there for, Rails will expect Admin::MessagesController to be located at app/controllers/admin/messages_controller.rb
# notice templates should be also inside "views/admin/messages"
<%= request.path %> --> /admin/messages
<%= params %> --> {"controller"=>"some/messages", "action"=>"index"}
<%= controller_path %> --> some/messages
<%= controller_name %> --> messages
<%= controller.class.name %> --> Some::MessagesController
- Forms
form_with model: [:admin, @article] --> admin_article_path(@article)
form_with model: [:admin, :management, @article]
---
# scope
#############
# no options
scope :admin do
resources :messages
end
# notice, there is a prefix for generated urls, but not for helper apis
# controller (messages_controller) doesn;t have to be inside admin folder
messages GET /admin/messages(.:format) messages#index
POST /admin/messages(.:format) messages#create
new_message GET /admin/messages/new(.:format) messages#new
edit_message GET /admin/messages/:id/edit(.:format) messages#edit
message GET /admin/messages/:id(.:format) messages#show
PATCH /admin/messages/:id(.:format) messages#update
PUT /admin/messages/:id(.:format) messages#update
DELETE /admin/messages/:id(.:format) messages#destroy
# <%= messages_path %> --> /admin/messages
<%= request.path %> --> /admin/messages
<%= params %> --> {"controller"=>"messages", "action"=>"index"}
<%= controller_path %> --> messages
<%= controller_name %> --> messages
<%= controller.class.name %> --> MessagesController
module
--------
# If you want to refer to a controller inside a module (controllers/admin/users_controller.rb)
# and the generated path without a prefix
# remember, controller and views have to be located inside folder admin, controller defined insid module admin
scope module: 'admin' do
resources :messages
end
messages GET /messages(.:format) admin/messages#index
POST /messages(.:format) admin/messages#create
new_message GET /messages/new(.:format) admin/messages#new
edit_message GET /messages/:id/edit(.:format) admin/messages#edit
message GET /messages/:id(.:format) admin/messages#show
PATCH /messages/:id(.:format) admin/messages#update
PUT /messages/:id(.:format) admin/messages#update
DELETE /messages/:id(.:format) admin/messages#destroy
# <%= messages_path %> --> /messages
<%= request.path %> --> /messages
<%= params %> --> {"controller"=>"some/messages", "action"=>"index"}
<%= controller_path %> --> some/messages
<%= controller_name %> --> messages
<%= controller.class.name %> --> Some::MessagesController
path
-----
# to add a prefix
scope module: 'admin', path: 'fu' do
resources :users
end
# this will a prefix 'fu' to controller 'admin/users_controller'
messages GET /fu/messages(.:format) admin/messages#index
POST /fu/messages(.:format) admin/messages#create
new_message GET /fu/messages/new(.:format) admin/messages#new
edit_message GET /fu/messages/:id/edit(.:format) admin/messages#edit
message GET /fu/messages/:id(.:format) admin/messages#show
PATCH /fu/messages/:id(.:format) admin/messages#update
PUT /fu/messages/:id(.:format) admin/messages#update
DELETE /fu/messages/:id(.:format) admin/messages#destroy
# <%= messages_path %> --> /fu/messages --> /admin/messages_controller
<%= request.path %> --> /fu/messages
<%= params %> --> {"controller"=>"some/messages", "action"=>"index"}
<%= controller_path %> --> some/messages
<%= controller_name %> --> messages
<%= controller.class.name %> --> Some::MessagesController
as
-----
# as can be used to change the name of the path method used to identify the resources.
scope module: 'admin', path: 'fu', as: 'cool' do
resources :messages
end
# cool will be added to path names
cool_messages GET /fu/messages(.:format) admin/messages#index
POST /fu/messages(.:format) admin/messages#create
new_cool_message GET /fu/messages/new(.:format) admin/messages#new
edit_cool_message GET /fu/messages/:id/edit(.:format) admin/messages#edit
cool_message GET /fu/messages/:id(.:format) admin/messages#show
PATCH /fu/messages/:id(.:format) admin/messages#update
PUT /fu/messages/:id(.:format) admin/messages#update
DELETE /fu/messages/:id(.:format) admin/messages#destroy
# Notice the name 'cool_messages' --> cool_messages_path
# <%= cool_messages_path %> --> /fu/messages and messages controller inside admin folder (module)
# controller names as above
- You can also add to which controller for example
scope :admin, controller: :messages do
get '/', action: :index
end
# same as
scope path: "admin", controller: :messages do
get '/', action: :index
end
GET /admin(.:format) messages#index
# Conclusion
# scope :name --> to set the prefix :name in generated urls
# path: to set the prefix in urls as above
# module: to set the module name that contains the controller
# as: to set the prefix in path names
- .:format
.:format allow us to pass extension to be used to influence the response from controller
- when calling /messages.json for example:
# check controllers_views referece
class MessageController < ApplicationController
def index
@message = Message.find(10
respond_to do |format|
format.html # index.html.erb
format.xml { render xml: @message }
format.json { render json: @message }
format.ics { render body: @message.to_ics, mime_type: Mime::Type.lookup("text/calendar") }
format.text { render :plain => "hello" }
end
end
end
- supported mime types: text types: json, xml, ics # calendar, html # default, css, js, csv, yaml
- application types: html, js, xml, yaml, atom, json, rss, url_encoded_form
get 'photos/:id', to: 'photos#show', defaults: { format: 'jpg' }
Cool Stuff
=============================
- objects = controller_name.classify.constantize.find(:all)
- instance_variable_set("@#{controller_name}", objects) # @names = objects
- controller_path.classify # Admin::Role
- controller_name.classify # Role
- self.class.name.sub("Controller","").singularize # NamesController -> Name
- Rails.application.routes.recognize_path "/orders/34"
{:controller => "orders", :action => "show", :id => "34"}
resource = "users"
resource.singularize.classify.constantize.find(id) -> User.find