在不同的发动机型号之间的ActiveRecord关系 [英] ActiveRecord relations between models on different engines

查看:111
本文介绍了在不同的发动机型号之间的ActiveRecord关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建一个Rails应用程序,很可能将有大量的模型。现在,让我们说,我需要的用户,每个用户都会有一个个人博客

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

我一直在开发与用户相关的部分在一个单独的引擎(让我们称之为AuthEngine),它封装了用户模型,验证等在当时这似乎是最好的办法

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

在同时,我的同事正在开发的发动机,对付博客功能(我们称之为BlogEngine)。 现在他需要访问存储在其它发动机用户数据。他通过定义来实现这一点:

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"

此方式,他可以很容易地询问用户数据,即使它没有被存储在相同的发动机。当我们要定义模型之间relashionships的问题就来了。

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

这样做的后果是,他不能做这样的事情 @ user.posts ,而是必须做 Post.find_all_by_user(@用户)

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)

有没有更优雅的方式来面对呢? 我还认为,每个引擎可以简单地生成应用程序内的车型,取出封装的可能性,但由于车型的数量将快速增长,我认为这将会使应用程序更乱,而不是尽可能多的maintanable

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

推荐答案

我想你应该以确定重新打开用户类中 blog_engine 的has_many :帖子的关系,它应该是适当的方式

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

这篇关于在不同的发动机型号之间的ActiveRecord关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆