不同数据库表的 ActiveRecord 继承

发布于 2024-07-18 03:42:27 字数 409 浏览 10 评论 0原文

我刚刚开始研究在 Rails 中使用更高级的模型。 我经常使用的一种模型非常成功,其中多对多交叉引用关系由一个类访问,该类本身是多对多关系中基类的子类。

这样,交叉引用类就可以充当基类的替代品。

一个很好的例子是导航层次结构节点 (NavigationNode) 与用户角色交叉引用。 在交叉引用点,类 (RoleNavigationNode) 可以继承自 NavigationNode,并且仍然对用户角色有深入的了解。

我的问题是(在上面的情况下)RoleNavigationNode 是否可以从 NavigationNode 继承并访问交叉引用表而不是 NavigationNode 访问的表——这当然是使用 ActiveRecord。

我没有研究过多态关联,这可能更合适。

提前致谢...,

I have just started investigating using more advanced models in Rails. One that I use regularly, with great success, is model where a many-to-many cross-reference relationship is accessed by a class that itself is a sub-class of the base class in the many-to-many relationship.

This way the cross-reference class can act as a stand-in for the base class.

A good example is where a navigation hierarchy node (NavigationNode) is cross-referenced to a user role. At the cross-reference point a class (RoleNavigationNode) can inherit from NavigationNode and still have intimate knowledge of the user role.

My question is (in the case above) can RoleNavigationNode inherit from NavigationNode and yet access the cross-reference table rather than the one that NavigationNode accesses -- this of course using ActiveRecord.

I have not investigated polymorphic association, which may be more appropriate.

Thanks in advance...,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野却迷人 2024-07-25 03:42:27

在子类上尝试过 set_table_name 吗?

另外,请研究在模型类中设置@abstract_class

最后,您需要的可能只是一个包含在两个模型中的 Mixin。

不管怎样,你想要做的事情听起来不太像 ActiveRecord 那样。 您可能想发布一个更清晰的示例来说明您想要实现的目标,也许我们能够想出更简单的东西。

tried set_table_name on the subclass?

Also, look into setting @abstract_class in model classes.

Lastly, what you need may simply be a Mixin that you include in both models.

Anyway, what you're trying to do sounds rather un-ActiveRecord-ish. You might want to post a clearer example of what you're trying to achieve, maybe we'll be able to come up with something simpler.

碍人泪离人颜 2024-07-25 03:42:27

这在 Rails 3 中有效:

class Common < ActiveRecord::Base
  @abstract_class = true
  def common
    "Foobar!"
  end
end

class Model < Common
end

class AnotherModel < Common
end

如果不设置 abstract_class,Rails 将在数据库中查找名为 commons 的表。

This works in Rails 3:

class Common < ActiveRecord::Base
  @abstract_class = true
  def common
    "Foobar!"
  end
end

class Model < Common
end

class AnotherModel < Common
end

Without setting abstract_class, Rails will look for a table named commons in your database.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文