Models, Modules, and Callbacks

There’s been some discussion about this before but I think I have a
unique problem.

I am trying to use modules with models to avoid naming conflicts while
connecting to more than one database.

Everything seems to be working ok in that we have:

  • Model definitions in models/namespace/model.rb
  • Controllers accessing models by Namespace::Model
  • Controllers loading models using « model ‘namespace/model’ »

The only problem I am having is callbacks like before_create,
after_create, etc seem to get called multiple times. For example…

module A
class B < ActiveRecord::Base
before_create :log_create

def log_create
  puts '>>> Creating...'
end

end
end

And then do A::B.create, I get multiple “>>> Creating…” messages,
but only one object in my table.

I am guessing because, in development, require_dependency loads the
file multiple times and the module mess things up somehow - my
callbacks keep piling on top of one another.

Thoughts?

JD

Thoughts?

The only thing that pops into my mind is a question. What type of
relationships does A::B have with other models (habtm, has_many,
etc…)?

I ran into similar problem when trying to use Modules with my models
and got no response from anyone so I’m not sure where the issue lies.
I had very strange behaviour when I tried doing this, with the class
basically getting loaded once, then forgotten about or lost somewhere
in the mist…its very odd.

Know this doesn’t help, but your not the only one having issues with
this at the moment. Anyone else have any thoughts on this? I find it
hard to believe everyone keeps the models on the top level namespace.

-Nick

The only thing that pops into my mind is a question. What type of
relationships does A::B have with other models (habtm, has_many, etc…)?

In my case, it has a belongs_to and a has_many, and it does use both
aggregation heavily. How might this complicate things? The callbacks
did not get called multiple times before we added the modules.