Skip to content

Instantly share code, notes, and snippets.

@FND
Created October 28, 2011 08:38
Show Gist options
  • Save FND/1321880 to your computer and use it in GitHub Desktop.
Save FND/1321880 to your computer and use it in GitHub Desktop.
test case for apparent bug regarding association inheritance
Gemfile.lock
#!/usr/bin/env ruby
# encoding: UTF-8
# test case for apparent bug regarding association inheritance
require "rubygems"
require "dm-core"
require "dm-constraints"
require "dm-migrations"
DataMapper::Logger.new($stdout, :debug)
DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/db.sqlite")
# models
class Company
include DataMapper::Resource
property :id, Serial
property :name, String, :required => true
has n, :vehicles, :constraint => :destroy
end
class LicensePlate
include DataMapper::Resource
property :id, Serial
property :registration, String, :required => true
end
class Vehicle
include DataMapper::Resource
property :id, Serial
property :type, Discriminator
property :name, String, :required => true
belongs_to :company
end
class Car < Vehicle
# `required => false` avoids FK property with a not-null constraint, which
# would prevent saving higher-level models
belongs_to :license_plate, :required => false
end
DataMapper.finalize
DataMapper.auto_migrate!
# generate data
Car.create :name => "KITT",
:company => Company.create(:name => "Knight Industries"),
:license_plate => LicensePlate.create(:registration => "KNIGHT")
# retrieve data
puts "\n[INFO] retrieving license plate via direct association"
puts "[INFO] ... via superclass"
p Vehicle.first # #<Car @id=1 @type=Car @name="KITT" @company_id=1 @license_plate_id=<not loaded>>
p Vehicle.first.license_plate # #<LicensePlate @id=1 @registration="KNIGHT">
puts "[INFO] ... via class"
p Car.first # #<Car @id=1 @type=Car @name="KITT" @company_id=1 @license_plate_id=1>
p Car.first.license_plate # #<LicensePlate @id=1 @registration="KNIGHT">
puts "\n[INFO] retrieving license plate via indirect association"
Company.first.vehicles.each do |vehicle|
p vehicle # #<Car @id=1 @type=Car @name="KITT" @company_id=1 @license_plate_id=<not loaded>>
p vehicle.license_plate # nil
puts "[ERROR] failed to retrieve license plate" if vehicle.license_plate.nil?
end
source :rubygems
DM_VERSION = "1.2.0"
gem "dm-core", DM_VERSION
gem "dm-constraints", DM_VERSION
gem "dm-migrations", DM_VERSION
gem "dm-sqlite-adapter", DM_VERSION
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment