Skip to content

Instantly share code, notes, and snippets.

@kirs
Created September 28, 2016 20:38
Show Gist options
  • Save kirs/e1c296c42f228df668d4b6af12d2c0af to your computer and use it in GitHub Desktop.
Save kirs/e1c296c42f228df668d4b6af12d2c0af to your computer and use it in GitHub Desktop.
require "bundler/setup"
require 'active_record'
require 'sqlite3'
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Schema.define do
create_table :gift_cards, force: true do |t|
t.references :checkout, null: false
t.string :code
end
create_table :checkouts, force: true do |t|
end
end
class GiftCardValidator < ActiveModel::Validator
def validate(model)
model.checkout.gift_cards.any?
puts "gift_cards: #{model.checkout.gift_cards.size}"
end
end
class Checkout < ActiveRecord::Base
has_many :gift_cards, dependent: :delete_all, inverse_of: :checkout, autosave: true
end
class GiftCard < ActiveRecord::Base
belongs_to :checkout
validates_with GiftCardValidator
end
checkout = Checkout.create!
checkout.gift_cards.create!(code: "sample")
checkout.gift_cards.create!(code: "sample")
# output:
# gift_cards: 0
# gift_cards: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment