Published on
1 min read

Standard for the Order of Associations, Scopes, Includes, and Validations in a Rails Model

Authors

Rails is all about 'Convention over Configuration'. There are community-driven Ruby coding style guides. While there is no strict enforced standard for the order of arranging model components, consistency is key. Here is the order I follow:

class Model < ActiveRecord::Base
  # all mixins
  include Something
  extend Something

  # constants
  MAX_LIMIT = 10

  # other stuff (macros)
  acts_as_taggable
  paginates
  attr_accessor :something

  # callbacks
  before_create :some_method

  searchable do
    text :something
  end

  # associations
  has_many :something
  belongs_to :something_else

  # validations
  validates_presence_of :something

  # scopes
  scope :something, -> { where(active: true) }

  # instance methods
  def instance_method
  end

  # class methods
  def self.class_method
  end

  # private methods
  private
  def method2
  end
end
TwitterLinkedInHacker News