Retrieving a Single Item from an STI Association

14 views
Skip to first unread message

Neil Chaudhuri

unread,
Feb 5, 2012, 12:48:25 AM2/5/12
to DataMapper
Let's say I have a Zookeeper (as in someone running a zoo and not the
Hadoop coordination software) entity that has an association of Animal
entities, which include Elephant, Monkey, and Giraffe subclasses. So I
have the following:

class Zookeeper
include DataMapper::Resource
.
.
.
has n, :animals
end



class Animal
include DataMapper::Resource

property :id, Serial
property :type, Discriminator
property :number_of_legs, Integer
property :created_at, DateTime
property :updated_at, DateTime
.
.
.
belongs_to :zookeeper
end



class Elephant < Animal; end
class Monkey < Animal; end
class Giraffe < Animal; end


I would like to add a method to my Zookeeper class that can get the
last Elephant added to the collection as defined by the created_at
property. I feel like outside the class I could do something like

Elephant.last(:zookeeper_id => id)

But I would like the method to be part of the Zookeeper class. I have
studied the documentation, but I can't find a use case where the
parent of an association wants to locate one particular child in the
association.

Any insight is appreciated.

Thanks.

Neil Chaudhuri

unread,
Feb 11, 2012, 11:30:48 AM2/11/12
to DataMapper
Just wanted to check in once again to see if any DataMapper users had
come across this. Long story short, I would prefer not to query my 1:M
collection of abstractions via
Animal.last(:type=>"Elephant", :zookeeper_id => id).

For one thing, I don't see the need to iterate over the entire Animal
table when I can just query the associations in the Zookeeper
instance.

For another, I don't like that such a method call tightly couples my
code to the ORM implementation details--in other words, knowing that
the foreign key is called zookeeper_id is a detail I shouldn't have to
know about lest that changes for whatever reason.

The preferable thing would be something, given the object model
described in my previous message, like
zookeeper.animals.last(:type=>"Elephant") or
zookeeper.animals.last(:elephant) or some such.

Is this possible now? How have you solved this problem if you've
encountered it?

Thanks.

mltsy

unread,
Feb 12, 2012, 11:31:40 PM2/12/12
to DataMapper
I don't see why zookeeper.animals.last(:type => 'Elephant') wouldn't
work, although I admit I haven't tried your code. Does that give you
an error?

You should also be able to use Elephant.last(:zookeper => zookeeper)
(you don't have to use zookeeper_id)

-Joe

Neil Chaudhuri

unread,
Mar 15, 2012, 1:13:49 AM3/15/12
to DataMapper
Thanks for pointing that out. I have gotten things working much more
elegantly now.
Reply all
Reply to author
Forward
0 new messages