Relation#map_to does nothing?

Learning site has:

class User
  attr_reader :attributes

  def initialize(attributes)
    @attributes = attributes
  end

  def [](name)
    attributes[name]
  end
end

users.by_pk(1).map_to(User)
# => #<User:0x007fa7eabf1a50 @attributes={:id=>1, :name=>"Jane"}>

This is not what happens.

Using the generic User code as above, and my watches relation posted in other threads, I get this:

query_mapped = WATCH_REPO.watches.by_pk(1).map_to(User)

puts query_mapped.inspect

#<Marv::SqlRelations::Watches name=ROM::Relation::Name(watches) dataset=#<Sequel::SQLite::Dataset: "SELECT `watches`.`id`, `watches`.`watch_type`, `watches`.`created_at`, `watches`.`updated_at` FROM `watches` WHERE (`watches`.`id` = 1) ORDER BY `watches`.`id`">>

It doesn’t map to the User class at all. What am I missing?

The documentation is incomplete. The mapping to the custom object happens when to_a is called.

query_mapped = WATCH_REPO.watches.by_pk(1).map_to(User).to_a

puts query_mapped.inspect

This will result in an array of User instances (length 1), similar to how it is shown in the documentation!

1 Like