Skip to content

Instantly share code, notes, and snippets.

@apetrov
Created December 13, 2018 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apetrov/0dad10168efbc32bcd91427a9416186e to your computer and use it in GitHub Desktop.
Save apetrov/0dad10168efbc32bcd91427a9416186e to your computer and use it in GitHub Desktop.
# Let's say user wants to charge a scooter.
class Charge
belongs_to :user
belongs_to :scooter
end
# we want to ensure that scooter is discharged
class Charge
belongs_to :user
belongs_to :scooter
validate do |charge|
charge.scooter.battery < 0.3 #or whatever magic number
end
end
Charge.new(user: user, scooter: scooter)
# that makes sense but when scooter changes this object is no longer valid.
# when objects become invalid overtime, things got messed up.
# Point:
# Validation could not depend on external objects.
# When there is more than 1 object in interaction, you need ensure
# that they could work together as a whole and it should be validated inside
# the application business logic/use case class but not in the model itself.
# Why does this point matter?
# Rails validation is another thing that have a tendency of being overused.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment