具有多对多关系的模型
我有一个测试应用程序,我正在尝试设置用于练习,该应用程序有用户,他们在注册时可以选择最多 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会使用 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.