Rails 中相同两个表上的两种不同类型的关联

发布于 2024-09-05 07:16:53 字数 326 浏览 1 评论 0原文

我有两个模型:用户和主题,目前我正在将它们加入到 theme_users 表中的 HABTM 关联中。基本上,用户创建新主题后,其他用户就可以选择该主题供自己使用。

但是,只有主题的原始创建者才有权编辑它。因此,我需要一些其他类型的关联来处理该关系,例如主题中的created_by_id字段。

通过这种方式,用户模型充当两个不同的角色:它们可以是主题的实现者和/或主题的所有者。实现者关系由themes_users连接表处理;问题是:处理这个二级关联的正确方法是什么?我是否需要使用户多态,然后使created_by_id引用成为“所有者”?或者有什么更容易的事情吗?

非常感谢您的帮助!

I have two models, users and themes, that I'm currently joining in a HABTM association in a themes_users table. Basically, after a user creates a new theme, it becomes available to other users to select for their own use.

However, only the original creator of the theme should have the ability to edit it. So, I need to have some other kind of association to handle that relationship, something like an created_by_id field in the theme.

In this way, the user model acts as two different roles: they can be an implementer of a theme AND/OR the owner of the theme. The implementer relationship is handled by the themes_users join table; the question is: What is the right way to handle this secondary association? Do I need to make users polymorphic and then make the created_by_id reference an "owner"? Or is there something easier?

Thanks so much for your help!

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

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

发布评论

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

评论(1

爱人如己 2024-09-12 07:16:53

我相信你应该添加以下关联

class User < ApplicationController
   # a user can create many themes
   has_many :themes_created, :foreign_key => :creator_id, :class_name => "Theme"
end

class Theme < ApplicationController
   # add a creator_id column in your themes table
   belongs_to :creator, :class_name => "User"
end

这样你就可以通过某些@user获取所有主题创建

@user.themes_created

I believe you should add the following association

class User < ApplicationController
   # a user can create many themes
   has_many :themes_created, :foreign_key => :creator_id, :class_name => "Theme"
end

class Theme < ApplicationController
   # add a creator_id column in your themes table
   belongs_to :creator, :class_name => "User"
end

This way you can get all the themes created by some @user through

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