Misha Moroshko
Misha Moroshko

Reputation: 171359

Rails: How to avoid a repetition of including the same module in several models?

I have several models that all include the same module:

class MyModel1 < ActiveRecord::Base
  include MyModuleName
end

class MyModel2 < ActiveRecord::Base
  include MyModuleName
end

class MyModel3 < ActiveRecord::Base
  include MyModuleName
end

Instead of including the module in each model, I tried to the following:

class MyNewModel < ActiveRecord::Base
  include MyModuleName
end

class MyModel1 < MyNewModel
end

class MyModel2 < MyNewModel
end

class MyModel3 < MyNewModel
end

but this ends up with an error saying that my_new_models table does not exist.

What is the proper way to avoid the repetition of include MyModuleName ?

Upvotes: 0

Views: 194

Answers (1)

idlefingers
idlefingers

Reputation: 32047

To get the model inheritance technique to work, you need to set self.abstract_class = true in MyNewModel:

class MyNewModel < ActiveRecord::Base
  self.abstract_class = true
  include MyModuleName
end

class MyModel1 < MyNewModel
end

class MyModel2 < MyNewModel
end

class MyModel3 < MyNewModel
end

Upvotes: 5

Related Questions