#79
Nov 11, 2007

Generate Named Routes

This more advanced episode will show you how to dynamically generate named routes by adding a method to the map object.
Tags: routing
Download (9.2 MB, 5:59)
alternative download for iPod & Apple TV (7.4 MB, 5:59)

Update: there’s now a plugin which does this called static_actions.

Resources

# routes.rb
ActionController::Routing::Routes.draw do |map|
  def map.controller_actions(controller, actions)
    actions.each do |action|
      self.send("#{controller}_#{action}", "#{controller}/#{action}", :controller => controller, :action => action)
    end
  end
  
  map.resources :products, :categories
  
  map.controller_actions 'about', %w[company privacy license]
end

RSS Feed for Episode Comments 55 comments

1. Brian Mitchell Nov 12, 2007 at 01:29

While I generally do use simple methods like you defined above on map, I will sometimes take a different approach for those types of urls.

I generally start applications by removing the :c/:a/:id style routes and add a "site" controller for general site topics. The routes file might look like this at first:

map.site ':action', :controller => 'site'

This works well enough since it can be used pretty cleanly:

site_path('jobs') #=> /jobs

There are some pros and cons here. One is that the actions can be added easily, which is a good thing in initial development... but if you like to strictly protect interfaces exposed on the web, then you can add some constraints on action:

map.site ':action', :controller => 'site', :action => /(jobs|sitemap|about)/

That regular expression will ensure only certain actions can get called ( the ()'s are required to correctly match given the |'s -- in 1.2 at least).

Finally, I should note that it is rather easy to add a formatted route as well:

# here is where things like with_options help a little.
map.site ':action', :controller => 'site'
map.site ':action.:format', :controller => 'site'

site_path('jobs') #=> /jobs
site_path('sitemap', 'xml') #=> /sitemap.xml

This might come in handy if you have several types of clients connecting to your service.

Of course, there are probably places where the overhead of these slightly more dynamic routes might be harmful.


2. Brian Nov 12, 2007 at 11:57

The one problem I keep having with routing is when you don't want the controller name in the route. For example, if you're doing a location based app, /texas/dallas/ is a lot more natural than /states/texas/cities/dallas. I do keep running in to a problem where two objects have the same scope, but you want to redirect to one if not found. i.e. /united-states/texas vs. /germany/munich. The way I've done this is ugly, but it works...kinda. Any suggestions would be helpful. I think there's a lot of voodoo with routing to most people.


3. Henrik N Nov 13, 2007 at 00:31

Brian: If worst comes to worst, you can have a catch-all route and do logic in a controller: http://railscasts.com/episodes/46

A very interesting, but pretty ugly/hackish way to use more powerful logic in your routes is http://www.ruby-forum.com/topic/42505.


4. lester bangs Nov 14, 2007 at 17:23

did you say "dick around" near the end there? ryan, i'm shocked! :)


5. James Nov 16, 2007 at 21:17

@lester - He said "dig around"! He has referred to "digging" in the past, so I am sure he is not a potty mouth. You have got your mind in the gutter! ;)


6. andré camargo Nov 16, 2007 at 23:40

Ryan, many thanks for every single episode. It's fantastic how you show the world of ruby, rails and the whole thing interact together. :-)

Keep your good work, thanks again!


7. Paul Barry Nov 19, 2007 at 06:32

It seems to me that this is meta just for the sake of being meta. Maybe that's just something you wanted to show in the screencast, but this seems like a cleaner way to do it:

%w{company privacy license}.each do |a|
  map.send "about_#{a}", "about/#{a}", :controller => 'about', :action => a
end


8. Ryan Bates Nov 20, 2007 at 10:20

@Paul, I agree this is an over-refactoring. It works best if you have quite a few of these kinds of actions in multiple controllers. That scenario was too complex for a simple screencast so I stuck with one controller.

In this case it's more about the technique then the circumstances to use it (which varies from project to project). I should have made that more clear.

@lester, LOL. I said "dig" around. I'll blame it on the cold I'm getting.


9. Drew Dec 06, 2007 at 12:43

Why create a method on map when you could simply send the actions to the map object?

def controller_paths(controller,*actions)
  actions.each do |a|
    map.send(#{controller}_#{a},#{controller/a},:controller => controller, :action => a)
  end
end

controller_paths :about, :company, :privacy, :liscense


10. Adrian Dec 11, 2007 at 01:19

A general question about routes:
Is there a naming convention between the route and the model relations?

model:
has_many usercomment
has_many usercomments, :through => usercomment

route:
map.resources :users do |users|
  users.resources :usercomments
end

Would this one work?


11. Sukhwinder Singh Tambar Sep 30, 2008 at 01:21

Really usefull cast...


12. kailas Feb 25, 2009 at 04:55

i'm trying to setup a route that's something like

map.connect ":foo/:controller/:action/:id", so i get :foo as a parameter.

that statement doesn't work in my routes.rb, but i'm a little confused about how to do it if it's possible at all (all the examples i've seen are of the form "controller"/"action"/[extra stuff]

any advice/suggestions would be greatly appreciated!

thanks!


13. Convert Database Sep 15, 2009 at 05:36

Non-destructive data base conversion tool is designed for converting source database records to destination database records.


14. group sms Sep 21, 2009 at 21:42

Offer pocket PC to mobile messaging software that is reliable solution to deliver text sms over all national or international mobile networks.


15. mobile forensics Sep 22, 2009 at 00:44

Recover sim card software restores recovered data and text messages in original form at user specified memory location.


16. generate barcode Sep 28, 2009 at 21:18

Barcode decoding software is easy to use program for both technical and non technical users


17. spy software Nov 01, 2009 at 21:28

Keylogger tool provides one of the easiest and secured ways to monitor keystroke activities in home or office in your absence.


18. data tool Nov 19, 2009 at 22:56

Offering sim card data recovery application recovers and restores ICC-ID identification number.


19. recover memory stick Nov 20, 2009 at 01:33

Ddiit.com provides excellent data recovery softwares at very low cost for all brands of memory cards.


20. Recovery Software Nov 23, 2009 at 02:52

Maker of FAT data recovery software retrieves deleted data from damaged FAT, VFAT, FAT12 files.


21. recovery partition Nov 25, 2009 at 02:51

Windows partition restores utility can recover lost and deleted audio, video and office documents files and folders without any hassle at user specific location.


22. purchase orders Dec 02, 2009 at 04:23

Developers of purchase order software that helps to manage entire billing reports in easily customizable format.


23. USB recovery Dec 03, 2009 at 20:54

Makers of usb drive file rescue application facilitate user to undelete files if Drive not formatted message is displayed by desktop.


24. laptop recovery Dec 03, 2009 at 21:43

Laptop hard disk recovery tool provides data backup from portable storage media like pen drive, memory card, thumb drive etc.


25. mobile messages Dec 11, 2009 at 21:44

Group text messaging software can generate and send job alerts, season greetings, contacting employees from PC to all mobile networks.


26. Recovery Software Jan 07, 2010 at 01:47

USB drive lost data recovery software restores lost or corrupted data files and folders from logically bad crashed memory stick, USB, thumb drive, pen drive, dongle, external USB, hard disk Drive or other USB removable disk drive.


27. file recovery free download Jan 18, 2010 at 20:25

Data recovery full download identify the contents of such lost files on the hard drive and allows you to recover them and If a file has been partially overwritten, File Recover attempts to reconstruct as much of the file as possible with the remaining contents.


28. file recovery free download Jan 18, 2010 at 21:02

Data recovery full download identify the contents of such lost files on the hard drive and allows you to recover them and If a file has been partially overwritten, File Recover attempts to reconstruct as much of the file as possible with the remaining contents.


29. data recovery tools download Jan 19, 2010 at 01:32

Data Recovery software free download is used to restore all lost data and it is designed to recover all the deleted files and folders at free of cost.


30. software documentation Jan 28, 2010 at 02:52

Provide software to enter image descriptions and support all picture file formats.


31. File recovery free Jan 29, 2010 at 23:25

To restore your absent mp3 files from your Zune music players download free file recovery software from filerecovery.in


32. data undelete Feb 01, 2010 at 01:09

Provides best efficient digital undelete data recovery software that retrieves deleted or corrupted pictures and images from memory card on camera.


33. Invoice software Feb 08, 2010 at 22:19

Providing inventory management application keep track on entire business process and make it smooth.


34. Key Logger Feb 15, 2010 at 23:53

It records keyboard inputs like user name, windows login passwords, active window text, typed characters in all messengers including YAHOO, MSN, AOL and ICQ.


35. picture recovery Feb 17, 2010 at 03:17

Browse image recovery software that is an economical tool and does not require any special knowledge to operate it.


36. Card Recovery Mar 03, 2010 at 22:17

Flash drive data recovery software recovers data lost due to accidental deletion, virus infected memory card, formatted or corrupted memory card and other similar data loss reasons.


37. Monitor USB Mar 10, 2010 at 04:13

To protect your data block USB ports on Windows PC using free usb disabler software.


38. barcode label Mar 12, 2010 at 23:22

Barcode label creator software provides you to generate barcode images of your own choice by allowing you to change shape, sizes as well as background colors.


39. restore windows Mar 19, 2010 at 23:03

Company provides <a href="http://www.drpu.com">Windows NTFS Partition Data Recovery Utility</a> to restore formatted music, pictures, image and audio video clips from hard disk drive.


40. Monitor USB Mar 24, 2010 at 02:23

Company provides data theft protection software to protect your computer from illegal USB device access.


41. Seo marketing services Apr 01, 2010 at 23:38

Affordable SEO and SEM services offers marketing strategies that will help your company reach its profitability goals.


42. Gang Apr 05, 2010 at 05:16

Bingo! thanks a lot.


43. Harry Fernandes Apr 13, 2010 at 04:08

We are industrial ventures provide quality grout in canada, shotcrete equipment, dry mix shotcrete in winnipeg canada.


44. office accounting software Apr 15, 2010 at 23:32

Company offers customizable accounting software with features like multi user support and transaction processing.


45. windows vista repair Apr 20, 2010 at 23:40

MMC Mobile card data rescue utility get back all corrupted office document files and compressed data.


46. recover digital photos Apr 21, 2010 at 02:20

Website provides Memory card photo recovery tool that allows instant retrieval of all lost pictures and videos of your loved ones from damaged multimedia card.


47. sachin Apr 21, 2010 at 23:29

key logger software


48. mobile forensics Apr 22, 2010 at 05:27

Mobile surveillance is simplest and easiest recovery application for retrieving lost details.


49. mobile forensics Apr 22, 2010 at 05:28

Mobile forensics application provides advance searching option for recovering lost details.


50. Recovery data May 14, 2010 at 23:56

Save accidentally lost, deleted and corrupted pictures, images, photos, movie clips and other data using advanced FAT data recovery software.


51. gucci sneakers May 28, 2010 at 02:20

good idea,i like it


52. helpdesk support Jun 09, 2010 at 05:07

Provides Aplus video to pocket PC software support video conversion and automatically detects hardware configuration.


53. Keylogger Tool Jul 01, 2010 at 03:48

Keylogger is completely undetectable superior stealth surveillance keyboard monitoring e-mail recording snapshots taking passwords capturing chat activities user friendly utility tool. Software supports windows 98/2000/NT/XP/VISTA. Its hidden from add remove program, start menu program task manager. All data save in an encrypted log file. Key logger key capturing software sends log report automatically to the specified email address. No technical skill is required to operate software. Key logger is best solution for concerned parents family member small and middle company or organization bank employees cyber cafe owner colleges/school/universities students big corporations need to monitor hundreds of employees simultaneously. Sanmaxi Keylogger Records voice chat in all messengers Records microphone sounds records all instant messaging conversations on AOL ICQ Yahoo and MSN. Key logger can restore previously typed text password and login account in case you have lost it. Monitoring Utility also helps to recover some important data which lost due to application crash like word excel power point notepad files.


54. Keylogger Program Jul 01, 2010 at 03:50

Key logger software secretly record keyboard activities typed passwords pressed keystrokes emails website urls microphone sound chat room conversation and all data are saved in encrypted log files. Key logger invisibly record all keystrokes and passwords and monitor internet activity.


55. Data Recovery Software Jul 01, 2010 at 03:52

Data recovery software retreive and recover all corrupted and formatted data from all corrupted formatted hard disk and any removable drives etc.


56. Key Logger Jul 01, 2010 at 03:53

Key Logger software runs invisibly and records keystrokes, capture screenshots, website urls, chat conversation, passwords emails and secretly track all activities performed on computer and laptop. Keyboard logger is compatible with all windows operating system Windows 98, Windows Me, Windows 2000, Windows 2003, Windows XP and Windows Vista.


57. Professional Windows Keylogger Jul 01, 2010 at 03:54

Key Logger Keyboard key logger keystroke recording software records retrieve keyboard typed data chat conversation and secretly track websites viewed email passwords record voice chat. Key logging tracker keyboard saver records everything that is typed on laptop and track keys pressed on computer. Completely hidden invisible keylogger keystroke catcher work on windows operating system.


58. Keylogger Software Jul 01, 2010 at 03:55

Key logger Program also supports slide show for screen snapshot pictures. Keyboard logger can automatic sent text log at your desired email address at a regular interval of time. You can also save your text log at your private folder on domain server by FTP Setting. Retrieve your lost information such as forgot password.


59. Vista Keylogger Jul 01, 2010 at 03:56

Keylogger Automatically records all keyboards activates typed emails chat conversations voice chat records and website visited user passwords.


60. evao Jul 02, 2010 at 04:23

Great thanks.


61. mobile marketing Jul 23, 2010 at 04:57

I came to this page by searching Yahoo. I have found it quite interesting. Thank you for providing this. I will have to visit here again!


62. mobile marketing Jul 27, 2010 at 04:56

Awesome post! Thanks for sharing such nice information with us. as a mobile marketing company, we'll send your blog link to our mobile subscriber to let them know about this great blog post.


63. text message marketing Jul 30, 2010 at 11:54

I hope you never stop! This is one of the best blogs Ive ever read. Youve got some mad skill here, man. I just hope that you dont lose your style because youre definitely one of the coolest bloggers out there. Please keep it up because the internet needs someone like you spreading the word.


64. dedicated short code Aug 02, 2010 at 10:27

You gave nice ideas here. I done a research on the issue and learnt most peoples will agree with your blog. Nice post to hang on..I really loved it the way of the stuff provided in this article..This has given very useful information..


65. free directory list Aug 11, 2010 at 22:23

I really appreciate what you post.


66. Air Jordan Force 4 Aug 22, 2010 at 23:00

Awesome post! Thanks for sharing such nice information with us. I am really interested in this learning about this. , I feel strongly about information and love learning more on this. Thanks for the information. This is a wonderful post!!


67. error fix Aug 24, 2010 at 08:30

I am sure he is not a potty mouth. You have got your mind in the gutter! ;)


68. louis vuitton shoes Aug 26, 2010 at 21:18

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it. My readers have about the same interets


69. hdd repair tools Aug 30, 2010 at 19:03

Thanks for sharing your article


70. snow boots Aug 31, 2010 at 00:46

I keep having with routing is when you don't want the controller name in the route.


71. louis vuitton sunglasses Sep 01, 2010 at 21:24

Very good post. Made me realize I was totally wrong about this issue. I figure that one learns something new everyday. Mrs Right learned her lesson! Nice, informative website by the way.

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source