Skip to content

Instantly share code, notes, and snippets.

@agrare
Created September 22, 2020 00:53
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 agrare/0164a34935d6aee5dadc0e85c635e5ef to your computer and use it in GitHub Desktop.
Save agrare/0164a34935d6aee5dadc0e85c635e5ef to your computer and use it in GitHub Desktop.
Before Validation Autosave
class Dog < ApplicationRecord
has_one :cat, autosave: true
before_save :ensure_cat
after_save :save_cat # Without this the before_validation on Cat isn't called
def ensure_cat
build_cat unless cat
end
def save_cat
cat.save!
end
end
class Cat < ApplicationRecord
belongs_to :dog
before_validation :it_worked!
def it_worked!
puts "it_worked!"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment