Is there something similar to application_helper or application_controller for models?

I have some functions that I use in each individual model, and I would like to put them in something like ActiveRecord::Base , so I won’t have to specify the same functions in all my models.

I'm not even sure if something like this is in line with best practices. Perhaps some Rails professionals might show me something better.

+4
source share
2 answers

Write a module containing the necessary methods, and include MyModule as needed.

You can certainly do as @derekerdmann suggested, and create an abstract base class for your models:

 class MyBaseModel < ActiveRecord::Base abstract_class = true def my_method(*args) #code goes here end end class MyModel < MyBaseModel end 

Remember that it assumes that the string abstract_class = true or single inheritance is inherited.

Personally, I prefer the mixin methodology, because if your models ever diverge in common functionality, you can group common functions into separate modules and include as needed.

+3
source

Remember that you can use standard object oriented methods in Rails. Create a class that extends ActiveRecord::Base with all your common features, and then extend this class for each of your actual ActiveRecord models.

+2
source

Source: https://habr.com/ru/post/1389773/


All Articles