Model classes in different folders

Hello,

I have the following structure:

  • app
    • controllers
      • helpdesk
        • call_controller.rb (Helpdesk::CallController <
          ApplicationController)
    • models
      • employee.rb
      • department.rb (Department < ActiveRecord::Base)
      • helpdesk
        • call.rb
        • call_history.rb (Helpdesk::CallHistory < ActiveRecord::Base)

Is it possible to have a relationship between call_history and
department? The problem is that they are in different folders (root and
helpdesk, respectively). I was thinking the mapping could be like this:

  • in call (has_many :call_history <- it’s working)

  • in call_history ( has_one: department <- it’s not working)

Could you help me?

Thanks in advance for any help!

Marcia

Marcia A. wrote:

Could you help me?

Move call.rb and call_history.rb up into the models folder :slight_smile:
Dan

why would you want to do this? It seems like you’re just asking for
trouble
by not following the rails standard for very little gain.

Hi Marcia,

a couple of points:

1 - if you’re not using rails1.1 this is probably going to cause you
grief - I wouldn’t bother.
2 - the simplest thing is to keep everything in the toplevel namespace
3 - there may come a point when your app is complex enough that the
complexity of namespaces is worth it to reduce clutter in your models
directory but
4 - it’s not worth it (imho) unless you’re being crushed under a
bazillion files in /app/models

That said, it is possible to do what you want, EXCEPT your use of a
‘helpdesk’ directory in controllers and a ‘helpdesk’ directory in
models. They will clash (at least they did the last time I had to
use namespaces) and there’s pretty much no way around it other than
to have different directory names for app/controllers and app/models.

So, just concentrating on the models, this ought to work:

in app/models/helpdesk/call.rb

class Helpdesk::Call < ActiveRecord::Base
has_many :call_history

works because ‘Helpdesk’ module is implied

and call_history.rb is in the helpdesk directory

end

in app/models/helpdesk/call_history.rb

class Helpdesk::CallHistory < ActiveRecord::Base
has_one :department, :class_name => ‘::Department’

you have to tell rails exactly where to find the

class you are referring to if it’s not in the current module

namespace

end

Note the :: in front of Department - it tells rails to look in the
toplevel namespace for the class named ‘Department’ - if you didn’t
have the ‘::’ characters it would assume the class is in the
‘Helpdesk’ module.

Also note that if, for example, Department (app/models/department.rb)
defines a relationship to something in the helpdesk directory then it
will need to fully specify the :class_name argument as well.

I hope this helps,

Regards,
Trevor

Trevor S.
http://somethinglearned.com