10

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.

Phantomwhale
  • 1,789
  • 1
  • 16
  • 30

2 Answers2

8

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.

coreyward
  • 77,547
  • 20
  • 137
  • 166
  • 2
    That didn't seem to adjust the contoller name, but adjusting it to `resources :implicit_tests, :controller => "tests", :path => "tests"` seemed to add that in. – Phantomwhale Jan 20 '12 at 02:25
1

Whilst looking at coreyward's answer, I stumbled across a shorter, but less intuitive method of getting what I need:

resources :tests, :as => "implicit_tests"

Are these essentially doing the same thing (given the extra :controller switch I added in the comments) ? Or is one preferred ?

Phantomwhale
  • 1,789
  • 1
  • 16
  • 30
  • You can certainly do this, too, but the mixed references to your Implicit Tests controller and model with names that don't really fit the "Rails Way" starts to get confusing. – coreyward Jan 20 '12 at 05:03
  • 1
    Ah ok, thought as much. Happy to try and stay as close to the rails way as I can, so I'll go with your answer. Might also go back to having an ImplicitTestController, to keep the number of routing options low, and to keep the controller name closer to the model name, which is probably better than keeping it closer to the path name; essentially what your suggesting above. – Phantomwhale Jan 21 '12 at 13:33