How to create Entity programmatically with relations?

Hey,

I need to create an Entity programmatically, but I have issues.

I have an entity Booking (id, name, area) which holds an Area (id, name) and I need to create this Bookings from hashes:

# relation
  module Relations
    class Bookings < ROM::Relation[:sql]
      schema(:cost_center_bookings, infer: true) do
        associations do
          belongs_to :area
        end
      end
    end
  end

# entity
module Entities
  class Booking < ROM::Struct
  end
end

module Entities
  class Area < ROM::Struct
  end
end
hash  = { id: 1, name: 'test', area: Area.new(id: 2, name: 'area1')

BookingsRepo.bookings.mapper.model.new(hash)
# returns { id: 1, name: 'test' }, the area is lost!

How is it possible to create a Booking-entity holding the area programmatically?

I tried to add the Area attribute explicitly:

module Entities
  class Booking < ROM::Struct
    attribute :area, Entities::Area.optional
  end
end

After that following works:

BookingsRepo.bookings.mapper.model.new(hash)
# returns { id: 1, name: 'test', area: { id: 2, name: "area1"} }

But then I cannot get Bookings from repo, without Area loaded.

Thank you for help!
PS: I don’t want to map to custom objects. I want to use auto_struct with custom struct classes.

You need to do bookings.combine(:area).mapper.model.new(hash). A booking without an area is not the same entity class as a booking with an area.

1 Like

Thank you! The more insight I get into ROM, the more awesome I find the object mapper. Thanks for the great work. Long live ruby :wink:

1 Like