Skip to content

Instantly share code, notes, and snippets.

@jordelver
Last active August 29, 2015 14:03
Show Gist options
  • Save jordelver/a92739062b5b26e28392 to your computer and use it in GitHub Desktop.
Save jordelver/a92739062b5b26e28392 to your computer and use it in GitHub Desktop.

What to put in ActiveRecord classes

Validations and relationships

Normal validations

  • Favour putting these into a Form Object once it becomes anything but the simplest example

Regular relationships (has_many, belongs_to etc)

Mutation

def set_published!
  self.published = true
  self.save!
end

Wrappers

Predicate methods and the like, for example

def bought_as_gift?
  payers.any? # payers is a relationship
end

Queries

Methods which do queries, for example

def self.newest_member
  where('member_id IS NOT NULL').order('created_at').last
end

This allows you to stub just the method #newest_member and more accurately models the domain

Don't use #where outside of ActiveRecord classes

Creation

Methods which just create object instances and save

def self.create_user!(email)
  create!(email: email, subscribed: true)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment