Relations II

In the previous section, we defined the relation between a user and their tweets. Matching between the incoming and outgoing relations, as well as naming them, was done automatically based on the related type. This default behaviour may not work so well in some cases:

  • We may want to maintain different types of relations between users and tweets. For example, tweets that a user created, and tweets that he/she retweeted.
  • What about a relation between objects of the same type? If the name is generated based on the type, we will not be able to distinguish between the outgoing and incoming relations.
  • In general, we may want to give our relation a meaningful name.

To make a long story short, we have a new requirement - We would like to be able to define custom names for our relations.

Defining the following relation

Our data model specifies that users should be able to follow one another. That is, we would like to define a many-to-many relation between users.

We will edit the code in lib/my_app/parts/user.rb, and add the following definitions to our User module.

to_many   :User, to: :follows
from_many :User, to: :follows, from: :followed_by
  • The to attribute is used for two purposes:
    • It defines the name of the outgoing relation.
    • It is used for matching an outgoing relation with its corresponding incoming relation. That is, xnlogic matches a to-relation with a from-relation that has the same to attribute.
  • The from attribute defines the name of the incoming relation.

At this point, we can access the follows and followed_by relations.

jruby-1.7.18 :021 > xget '/model/user/id/73/rel/follows'
jruby-1.7.18 :022 > xget '/model/user/id/73/rel/followed_by'

Note: Don’t forget to reload any code changes to the console, using MyApp.reload!.


  • We can define custom names for our relations.
  • The to attribute defines the name of a to-relation, and is used for matching it with the corresponding from-relation.
  • The from attribute defines the name of a from-relation.

At this point, we know how to define relations, and access them via the API. In the next section, we will learn about actions, that will allow us to change (create/update/delete) our relations.