Created
September 28, 2016 20:38
-
-
Save kirs/e1c296c42f228df668d4b6af12d2c0af to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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