Last active
June 21, 2024 15:53
-
-
Save caius/0f1f289522a69b713883c2eaf9f77784 to your computer and use it in GitHub Desktop.
`after_create_commit` can be invoked twice
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
gem "sqlite3", "~> 1" | |
require 'sqlite3' | |
gem "activerecord", "~> 7.1" | |
require 'active_record' | |
# Set up a database that resides in RAM | |
ActiveRecord::Base.establish_connection( | |
adapter: 'sqlite3', | |
database: ':memory:' | |
) | |
# Set up database tables and columns | |
ActiveRecord::Schema.define do | |
create_table "attachments", force: :cascade do |t| | |
end | |
create_table "blobs", force: :cascade do |t| | |
t.belongs_to :attachment | |
t.boolean :analyzed, default: false | |
end | |
end | |
puts | |
puts | |
# Set up model classes | |
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
end | |
class Attachment < ApplicationRecord | |
has_one :blob | |
after_create_commit :analyze_later_callback | |
def analyze_later_callback | |
puts "#{self.class}##{__method__}" | |
blob.analyze_later | |
end | |
end | |
class Blob < ApplicationRecord | |
belongs_to :attachment | |
after_create_commit :scan_blob | |
def analyze_later | |
puts "#{self.class}##{__method__}" | |
update!(analyzed: true) unless analyzed | |
end | |
def scan_blob | |
puts "#{self.class}##{__method__}" | |
end | |
end | |
Attachment.create!(blob: Blob.new) | |
# >> -- create_table("attachments", {:force=>:cascade}) | |
# >> -> 0.0068s | |
# >> -- create_table("blobs", {:force=>:cascade}) | |
# >> -> 0.0002s | |
# >> | |
# >> | |
# >> Attachment#analyze_later_callback | |
# >> Blob#analyze_later | |
# >> Blob#scan_blob | |
# >> Blob#scan_blob | |
Attachment.all | |
# => [#<Attachment:0x00000001208cc1e0 id: 1>] | |
Blob.all | |
# => [#<Blob:0x00000001208cba60 id: 1, attachment_id: 1, analyzed: true>] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment