且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单个 Rails 模型中引用的多个外键

更新时间:2023-12-02 21:00:04

从代码可维护性的角度来看,即使您可能希望将用户现在可以选择的类别数量限制为 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.