Skip to content

Instantly share code, notes, and snippets.

@theCrab
Created August 5, 2013 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theCrab/a5602852bc2e6a70ae4d to your computer and use it in GitHub Desktop.
Save theCrab/a5602852bc2e6a70ae4d to your computer and use it in GitHub Desktop.
How would I build a better relationship? Whenever I create a license for a person, I have to pass in a vehicle relation too.
class Vehicle
include DataMapper::Resource
property :id, Serial
property :registration, String, required: true
property :make, String, required: true
property :type, Enum[:saloon, :mpv], default: :saloon # anything above 4(passengers) == :mpv
property :date_of_reg, Date, required: true
property :number_of_seats, Integer, required: true
property :driver_1, Integer, required: true
property :driver_2, Integer
property :owner_id, Integer
property :owner_type, Enum[:person, :organisation], default: :person
property :created_at, DateTime
property :updated_at, DateTime
has n, :licenses
has n, :mileages
def driver
Person.get(self.driver_1)
end
def drivers
Person.all(id: [self.driver_1, self.driver_2])
end
def owner
type = self.owner_type
raise OwnerTypeError, 'The owner_id or owner_type are not available' unless type
case type
when :organisation
driver = Organisation.get(self.owner_id)
when :person
driver = Person.get(self.owner_id)
end
driver
end
end #Vehicle
###---Error Class --
class OwnerTypeError < StandardError
end #OwnerTypeError
class License
include DataMapper::Resource
property :id, Serial
property :number, String , required: true
property :provider, String, required: true
property :starts_on, Date, required: true
property :expires_on, Date, required: true
property :type, Enum[:driving, :insurance, :mot, :road_tax], default: :driving
property :active, Boolean, default: false
belongs_to :person, required: false
belongs_to :vehicle, required: false
# belongs_to :company
end
p = Person.get(1)
v = p.linceses.create!(number: 'KILO123RG', provider: 'DVLA', starts_on: Date.today, expires_on: Date.today + 135, active: true)
v.errors # => DataMapper::SaveFailure, vehicle_id cannot be blank
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment