Skip to content

Instantly share code, notes, and snippets.

@ltw
Created September 22, 2015 15:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ltw/956d068f12c13c70acc4 to your computer and use it in GitHub Desktop.
Save ltw/956d068f12c13c70acc4 to your computer and use it in GitHub Desktop.
ActiveRecord Breakout Code Notes
# id | user_id
class Profile
belongs_to :user
# is actually:
# def user
# User.find_by(id: self.user_id)
# end
end
# id
class User
has_one :profile
# is actually:
# def profile
# Profile.find_by(user_id: self.id)
# end
has_many :posts, foreign_key: 'author_id'
# is actually:
# def posts
# Post.where(author_id: self.id)
# end
has_many :comments, foreign_key: 'commenter_id'
# is actually:
# def comments
# Comment.where(commenter_id: self.id)
# end
has_many :post_comments, through: :posts, source: :comments
# is actually:
# def post_comments
# self.posts.map {|p| p.comments }
# end
end
# id | author_id
class Post
belongs_to :author, class_name: 'User'
# is actually:
# def author
# User.find_by(id: self.author_id)
# end
has_many :comments
# is actually:
# def comments
# Comment.where(post_id: self.id)
# end
end
# id | post_id | commenter_id
class Comment
belongs_to :post
# is actually:
# def post
# Post.find_by(id: self.post_id
# end
belongs_to :commenter, class_name: 'User'
# is actually:
# def commenter
# User.find_by(id: self.commenter_id)
# end
# conceptually equivalent to belongs_to :through (which doesn't exist)
def post_author
post.author
end
end
id | name | email | age | password_hash
class User
MAX_AGE = 130
# name must exist
validates :name, presence: true
# email must exist and be in the right format
validates :email, format: { with: /.+\@.+\..+/, message: 'is not in the correct format' }, uniqueness: true
# age must be a number but doesn't have to exist, but must also be in the possible ages of humans
validates :age, numericality: { only_integer: true }, inclusion: { in: (0..MAX_AGE), message: 'is not a human age' }
# password hash must exist
validates :password_hash, presence: true
# if a user is over the age of 15, they must have an email
validate :age_must_have_email
private
def age_must_have_email
if age > 15 && email.empty?
errors.add(:email, 'must be present when over the age of 15')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment