ActiveRecord relations between models on different engines

橙三吉。 提交于 2019-12-10 20:24:08

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/11704106/activerecord-relations-between-models-on-different-engines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!