Elixir tip: relationship names of classes in other modules

Almost all examples of Elixir code have all the Entity classes in the same module, for example:

class User(Entity):

    has_many('newsitems', of_kind='NewsItem')

class NewsItem(Entity):

    belongs_to('author', of_kind='User')

However, I personally find that once you get beyond 3-4 classes in the same module it gets a bit unwieldy, moreso if you add additional methods to those classes. Although I dislike the way that Rails’ ActiveRecord encourages one file per class (actually,there is a lot I dislike about the way Rails does class loading, but that’s the subject for another post) I prefer to group model classes into logical modules.

However, one thing to remember when using Elixir, the of_kind argument in belongs_to, has_many, etc must then take the full module path name rather than just the class name, so if we split up the above code into two files, myapp/models/user.py and myapp/models/news.py, we would do this:

myapp/models/user.py:

class User(Entity):

    has_many('newsitems', of_kind='myapp.models.news.NewsItem')

myapp/models/news.py:

class NewsItem(Entity):

    belongs_to('author', of_kind='myapp.models.user.User')
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s