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:
To make a long story short, we have a new requirement - We would like to be able to define custom names for our relations.
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
to
attribute is used for two purposes:
to
attribute.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!
.
to
attribute defines the name of a to-relation, and is used for matching it with the corresponding from-relation. 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.