Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write routing when resource model name does not match path or controller

I've got a model called ImplicitTest. It's called this as having a Ruby object called Test just breaks a lot of things in Rails.

However, I still want to expose it as a RESTful resource as test (e.g. /tests, /test/1/edit and so forth). Furthermore, it would be great to keep the controller as TestsController, although that's less important.

I was doing this by having simple resources :tests line in my routes.rb file, but this fails for the RESTful forms (e.g. <%= form_for @test ... > - this picks up that the @test object is of type ImplciitTest, and tries to lookup implicit_test_path which does not exist.

I tried adding form_for options, but came to the conclusion that to have the form work for both new and edit actions, there was no one single, unified way of asking form_for() to use a different prefix for the path name lookup.

So I've been trying to approach the problem from the routing side. Is there a line I can add to the routes file that will allow me to:

  1. Have a model called ImplicitTest
  2. Have the path as /test
  3. Use the <%= form_for @test ... %> tag still
  4. Keep the controller as TestsController (optional)

I know I am departing the Golden Path to do this, but Rails isn't letting me use Test as a model name, but this is the name users will expect to see in the URL for this resource, so I'm hoping there is are simple routing option(s) that enable this.

like image 582
Phantomwhale Avatar asked Jan 20 '12 01:01

Phantomwhale


1 Answers

All you need to do is set the :path option on your route:

resources :implicit_tests, :path => '/test'

You would still use the standard implicit_tests_path helper this way, too, so your code doesn't have to diverge to alter the URL scheme.

like image 108
coreyward Avatar answered Sep 24 '22 21:09

coreyward