Ruby DataMapper aliased associations

In Ruby’s DataMapper ORM you can easily associate one type of object with another, e.g. an Image can have many Tags. For the most part DM takes care of the issue of pluralization, ie. if your tag object is Tag then the associated tag collection is accessed as image.tags

However, what if you want to use a completely different name? I needed to do this recently and struggled to find any help in the DM documentation. As it turns out, it’s very simple. There’s an (AFAIK undocumented) option when defining associations where you can specify the class name of the target model for the relationship. Let’s say you have Person and Book objects and you want a one-to-many relationship between people and books called reading, you simply include the model option.

Simple 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">