开发者

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

开发者 https://www.devze.com 2023-02-08 06:34 出处:网络
I have several models that all include the same module: class MyModel1 < ActiveRecord::Base include MyModuleName

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 &l开发者_开发问答t; 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 ?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消