单个 Rails 模型中引用的多个外键 [英] Multiple foreign keys referenced in a single Rails model

查看:56
本文介绍了单个 Rails 模型中引用的多个外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个典型的用户模型(用户名、密码、姓名等).我希望允许用户将三个选定的类别附加到他们的帐户中.三个类别中的每一个都存在于类别模型中.

I have a typical User model (username, password, name, etc). I want to allow users to attach three chosen categories to their account. Each of the three categories exist in the Category model.

如何在不使用中间表进行跟踪的情况下将类别中的三个外键链接到单个用户?每个类别可以属于任意数量的用户,但每个用户只能拥有三个类别.

How can I link three foreign keys from Category to a single User without using an intermediate table for tracking? Each Category can belong to any number of Users, but each user can have only three Categories.

我玩过 has_many :through 但我真的不认为关系表是必要的,它会在我的一端生成很多编码来使用它.

I played with has_many :through but I really don't think a relationship table is necessary and it would generate a lot of coding on my end to work with it.

有什么想法吗?

推荐答案

从代码可维护性的角度来看,即使您可能希望将用户现在可以选择的类别数量限制为 3,但您可能不想对其进行编码有了这个限制.稍后当您想将其增加到 5 或减少到 1 时,您会很自责.我的建议是将 has_and_belongs_to_many 与连接表一起使用(您不需要 :通过 因为,据我所知,您不需要连接模型,只需要一个连接表).使用 HABTM 将自动使用连接表,因此您不必担心编写代码来处理它.只需确保正确命名连接表及其列.

From a code maintainability standpoint, even though you may want to restrict the number of categories a user can pick to 3 right now, you may not want to code it with this limitation. You'll be kicking yourself later when you want to increase it to 5 or reduce it to 1. My suggestion would be to just use has_and_belongs_to_many with a join table (you don't need :through because, from what I can tell, you don't need a join model, just a join table). Using HABTM will automatically use a join table so you don't have to worry about writing the code to handle that. Just make sure you name the join table and its columns properly.

至于实际上将用户限制为 3 个类别,只需在视图/控制器中实现该限制(即限制 UI,使他们不能选择超过 3 个).

As for actually restricting the user to only 3 categories, just implement that restriction in the view/controller (i.e. restrict the UI so they can't choose more than 3).

我确定你已经读过这篇文章,但如果你还没有读过,这里是 文档 HABTM.

I'm sure you've already read this, but in case you haven't, here's the docs for HABTM.

这篇关于单个 Rails 模型中引用的多个外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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