Hey,
I was just looking around rails and noticed there is an app controller but no app model.
Is there no root model in rails ? if not where do you put a piece of code that needs to be in every model.
Thanks, Alex
Hey,
I was just looking around rails and noticed there is an app controller but no app model.
Is there no root model in rails ? if not where do you put a piece of code that needs to be in every model.
Thanks, Alex
Most models in rails inherit from ActiveRecord::Base which has all of the conventional getters and setters and the association methods, validations and support.
You could extend ActiveRecord::Base in a file in the lib directory (or anywhere in the rails load path really) and any models that are active record models would have the method(s) available. Modules are also a good way of sharing code between many models.
Nothing says your controllers have to subclass ApplicationController
but it generally is the standard because the vast majority of rails applications make use of the layout
capabilities (which can vary on each controller), so instead of forcing the rare ones without layouts from turning the layout off (layout nil
or layout false
) for each controller, they make an 'abstract' one that you can turn controller features on and off easily for your whole application.
Now for models, you could create an ApplicationModel
for all of your models to subclass, but there are two things to think about:
ActiveRecord::Base
and uses this to turn STI (single table inheritance) on.ApplicationModel
will be an actual model that is expected to have a table in your database. This can lead to problems down the line.To fix these two problems, you have to set abstract_class
to true for ActiveRecord to properly function.
def ApplicationModel < ActiveRecord::Base
self.abstract_class = true
end
In contrast to an abstract ActionController, abstract_class
must set to true which means the developer must know they cannot remove this line from ApplicationModel
. With ApplicationController
you can do pretty much whatever you want to it.