具有多对多关系的模型

发布于 2024-12-20 02:13:19 字数 469 浏览 6 评论 0原文

我有一个测试应用程序,我正在尝试设置用于练习,该应用程序有用户,他们在注册时可以选择最多 6 个兴趣类别。

所以,用户可以有很多兴趣类别,这将有很多“子”兴趣...我有点困惑如何设置它,以便当用户注册时,他们可以选择 6 个兴趣类别用户注册表单上的复选框方式。

我应该使用多态关联,还是应该使用用户模型和 interest_category 模型创建兴趣和 interest_category 模型,例如:

has_many :interest_categories, :through => :interests ?

另外,我如何获取表单保存这些interest_categories?我尝试过 f.fields_for :interest_categories,但它们没有保存。

有什么想法吗?

I have a test app that I'm trying to setup for practice, the app has Users, who can choose up to 6 Interest Categories when they register.

So, the user can have many interest categories, which will have many "sub" interests ... I am a little confused as to how I can set this up, so that when the user registers, they can choose the 6 interest categories by way of checkboxes on the user registration form.

Should I be using polymorphic associations, or should I create an interest and interest_category model with the user model and the interest_category model using something like:

has_many :interest_categories, :through => :interests ?

Also, how can I get the form to save these interest_categories? I've tried f.fields_for :interest_categories, but they aren't saving.

Any ideas?

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

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

发布评论

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

评论(1

你好,陌生人 2024-12-27 02:13:19

我会使用 has_many :categories, :through =>; :可分类。然后,您可以将一个名为 :category_type 的字符串字段添加到可分类模型中,并针对这种情况输入“interest”,针对其他情况输入另一个字符串。

通过这种方式,您将拥有一个与关系类型无关的多通关系。

然后,您可以通过 User.categorizables.where(:category_type => "interest") 进行查询或设置范围。

您可能还想考虑观看此 Railscast:http://railscasts.com/episodes/17-habtm -checkboxes

它有点过时,但很可能对设置您的表单有帮助。有很多方法可以解决这个问题,但这就是我要做的。

I would use has_many :categories, :through => :categorizables. You could then add a string field called :category_type to the Categorizable model and input "interest" for this case and another string for other cases.

In this way you would have a has many through relationship that's agnostic to the relationship type.

You can then query by User.categorizables.where(:category_type => "interest") or setup a scope.

You also might want to consider watching this Railscast: http://railscasts.com/episodes/17-habtm-checkboxes

It's a little outdated, but most likely helpful in setting up your form. There's many ways to approach this, but that's how I'd do it.

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