Subfolders in Rails applications (newbie)

After about a week playing with Rails, I have built a couple of apps but
am still unable to get one thing to work: subfolders. (I am probably
using the wrong term here, but oh well…)

I would like my rails application to have controllers logically grouped
into folders. So for instance:

http://domain.com/accounting/accounts
http://domain.com/hr/employees

Here’s how I have tried to accomplish this:

  1. Create folder ‘accounting’ in /app/controllers/
  2. In /app/controllers/accounting, create ‘accounts_controller.rb’
    class AccountsController < ApplicationController
    def index
    end
    end
  3. Create folder ‘accounting’ in /app/views/
  4. Create folder ‘accounts’ in /app/views/accounting/
  5. In /app/views/accounting, create ‘index.rhtml’

    Testing accounting accounts index

  6. Create folder ‘accounting’ in /app/helpers/
  7. In /app/helpers/accounting, create ‘accounts_helper.rb’
    module AccountsHelper
    end

Then if I fire up WEBrick and navigate to URL
http://localhost:3000/accounting/accounts, I ge the following error:

LoadError in #
Already loaded file
‘./script/…/config/…/app/controllers/accounting/accounts_controller.rb’
but ‘AccountingController’ was not set, perhaps you need to rename
‘./script/…/config/…/app/controllers/accounting/accounts_controller.rb’?

Any help would be appreciated. Right now I have resorted to having ALL
of my controllers in the same directory and using grotesquely long
names, i.e.

http://domain.com/accounting_accounts

which violates the principle of pretty urls.

On 12/17/05, PWills [email protected] wrote:

After about a week playing with Rails, I have built a couple of apps but
am still unable to get one thing to work: subfolders. (I am probably
using the wrong term here, but oh well…)

The default route, ‘:controller/:action’, should give you the URLs you
ask for without much complication. If you have a controller
‘accounting’ with an action ‘accounts’ then the URL (given by the
default route) is ‘/accounting/accounts’.

Sincerely,

Tom L.
[email protected]
http://AllTom.com/

To properly get automatic subfolders like this, you need to put your
controllers inside a scope.

For example, if /app/controllers/accounting/accounts_controller.rb is
supposed to be mapped to accounting/accounts, that file needs to define
a class like so:

class Accounting::AccountsController < ApplicationController

Similarly, you want to define your employees controller as:

class Hr::EmployeesController < ApplicationController

Just be aware that linking between scopes is a little tricky sometimes,
but you should be able to get it with some trial and error (also, tests
are your friend)

The other option if you don’t have many controllers would be to hard
code some routes with the longer controller name.

  • Jamie