Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JaredShay/73a9425ac0bb8e10d085a2b617140152 to your computer and use it in GitHub Desktop.
Save JaredShay/73a9425ac0bb8e10d085a2b617140152 to your computer and use it in GitHub Desktop.
require 'active_record'
require 'pg'
require 'active_record_inherit_assoc'
# set up database
PG_SPEC = {
adapter: 'postgresql',
database: 'inherit_test_db'
}
ActiveRecord::Base.establish_connection(PG_SPEC.merge('database' => 'postgres', 'schema_search_path' => 'public'))
ActiveRecord::Base.connection.drop_database PG_SPEC[:database] rescue nil
ActiveRecord::Base.connection.create_database(PG_SPEC[:database])
ActiveRecord::Base.establish_connection(PG_SPEC)
# Set active record logger to STDOUT to see executed SQL
ActiveRecord::Base.logger = Logger.new(STDOUT)
# define migration to set schema
class CreateModels < ActiveRecord::Migration
def self.change
create_table :users do |t|
t.integer :some_attr
t.timestamps
end
create_table :accounts do |t|
t.integer :user_id
t.integer :some_attr
t.timestamps
end
end
end
# run migrations
CreateModels.change
# define models and populate db
class User < ActiveRecord::Base
has_one :account, inherit: [:some_attr]
end
class Account < ActiveRecord::Base
belongs_to :user
end
user = User.create!(some_attr: 1)
account = Account.create!(user_id: user.id, some_attr: 1)
user.account # dirty the statment cache
user_2 = User.create!(some_attr: 2)
account_2 = Account.create!(user_id: user_2.id, some_attr: 2)
puts user_2.account.inspect # nil as the SELECT statement uses the `some_attr` value from the previous call.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment