Learn Ruby on Rails Book

Order of items on Active Record Models

Let's look at following code which is not related to this project.

1class User < ApplicationRecord
2
3  def to_lowercase
4    email.downcase
5  end
6
7  before_save :to_lowercase
8
9  VALID_EMAIL_REGEX = /\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
10  validates :email, presence: true,
11                    length: { maximum: 255 },
12                    format: { with: VALID_EMAIL_REGEX },
13                    uniqueness: { case_sensitive: false }
14
15  validates :first_name, presence: true, length: {maximum: 50}
16  validates :last_name, presence: true, length: {maximum: 50}
17end

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

https://github.com/rubocop-hq/rails-style-guide#macro-style-methods is a good reference for this.

Now we can rearrange the above to look like this:

1class User < ApplicationRecord
2  VALID_EMAIL_REGEX = /\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
3  validates :email, presence: true, length: { maximum: 255 },
4    format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
5
6  # validates :first_name, presence: true, length: {maximum: 50}
7  # validates :last_name, presence: true, length: {maximum: 50}
8  
9  before_save :to_lowercase
10
11  private 
12  
13  def to_lowercase
14    email.downcase
15  end
16end

Now let's commit these changes:

1git add -A
2git commit -m "Added email validations"