Naps62
Naps62

Reputation: 970

ActiveRecord relations between models on different engines

I'm building a Rails app that is probably going to have a large amount of models. For now let's say that i need to have Users, and each User will have a personal Blog

I've been developing the User-related part on a separate Engine (let's call it AuthEngine) that encapsulates the User model, authentication, etc. At the time this seemed like the best approach

In parallel, my colleague was developing another engine, to deal with the blog features (let's call it BlogEngine). Now he needs to access user data which is stored in the other engine. He achieved this by defining:

BlogEngine.user_class = "AuthEngine::User"

This way, he can easily ask for user data, even though it isn't stored in the same engine. The problem comes when we want to define relashionships between models

He can easily say that each blog post belongs to a user

has_one :user, :class_name => BlogEngine.user_class

But as far as i know he can't specify that each User has multiple posts since the User model is within the other engine

The consequence of this is that he can't do things like @user.posts, but instead has to do Post.find_all_by_user(@user)

Is there a more elegant way to deal with this? I also considered the possibility that each engine could simply generate the models inside the app, removing the encapsulation, but since the amount of models will grow quickly, i think this will make the app more of a mess, and not as much maintanable

Upvotes: 3

Views: 665

Answers (2)

Arthur Alkmim
Arthur Alkmim

Reputation: 237

What about having a common models gem/engine with only the relationships as a dependency for your engines? This way you would have access to all relevant relationships in every engine.

Upvotes: 0

Sandip Ransing
Sandip Ransing

Reputation: 7733

I think you should reopen user class inside blog_engine in order to define has_many :posts relation and it should be appropriate way.

Upvotes: 2

Related Questions