We know that Rails 5 added ApplicationRecord
as an abstract class which was inherited by our models (ActiveRecord).
But basically, I think every technical requirement we do with ApplicationRecord, we can also do with ActiveRecord::Base
. For instance:
module MyFeatures
def do_something
puts "Doing something"
end
end
class ApplicationRecord < ActiveRecord::Base
include MyFeatures
self.abstract_class = true
end
So now every model will be attached the behaviors of MyFeatures
. But we can also achieve this in Rails 4:
ActiveRecord::Base.include(MyFeatures)
So what is the benefit of using ApplicationRecord
, do you think it is necessary to add ApplicationRecord
?
While it may seem the same in basic Rails applications, there actually is an important difference once you begin to use rails engines, plugins / gems or direct methods from ActiveRecord::Base
.
ActiveRecord::Base.include(MyFeatures)
mixes in the features directly into ActiveRecord::Base
and it is present there forever for all later uses of ActiveRecord::Base
(it cannot be "unmixed") and there is no way to get the original ActiveRecord::Base
anymore in any code after the include. This can easily lead to problems if some of the mixed in feature changed the default ActiveRecord behavior or if e.g. two engines / gems tried to include same-named methods.
On the other hand, the ApplicationRecord
approach makes the features present only for the classes (models) that inherit from it, other classes, as well as direct use of ActiveRecord::Base
stay pristine, uncluttered by the module features.
This is especially important when engines or rails plugins are used as it allows them to separate their own model logic from the main application's model logic which was not possible before ApplicationRecord
.
All of this is also nicely described in this blog post and this github comment.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments