In this chapter we are going to discuss how Active Record models should be
structured.
Let's start by looking into the unordered definition of the User
model, which
will work, but has the potential to cause a lot of harm and debugging issues in
the future.
Note that the following is an example of how we shouldn't structure our model:
Items should be presented in an order
Above code works but the Rails community has agreed upon certain order in which
items should be presented. And the order goes something like this:
- default_scope
- constants
- attr_*
- enum
- associations
- validations
- callbacks
- other macros (like devise's, has_secure_password) should be placed after the
callbacks
- public methods
- private methods
The
RuboCop Rails style guide
is a good reference for this.
Now we can rearrange the above to look like this:
Let's take a look at the User model in our Granite application. If you recall we
updated the User model in
Adding comments to a task
chapter to:
We can see that all the items are in correct order inside the User model.
Ideally, we should go through all our models and make sure that the ordering is
taken care of. But for the time being let's focus on creating our application.
In the upcoming chapters let's try to add Rubocop
rules which can do this job
or at least warn us, when ordering is not correct.
After going through the User model and refactoring it (if required), commit the
changes: