Rails 3 中的多对多关系
我在 Rails 中创建了 2 个模型,并修改了模型类以添加多对多关系(使用 has_and_belongs_to_many
)
class User < ActiveRecord::Base
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :users
end
当我通过 Web 界面创建用户时,系统不会要求我选择某些类别。
我错过了什么吗?我读到需要另一个表,但它似乎是在 has_many
的情况下,而不是 has_and_belongs_to_many
语句)。
你能帮忙吗?
我认为这是一个新手问题,但是......
非常感谢,
问候,
Luc
I have created 2 models in rails and modified the models classes to add a many to many relationship (with has_and_belongs_to_many
)
class User < ActiveRecord::Base
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :users
end
When I create a User though the web interface, I am not asked to select some categories.
Did I miss somthing ? I read that another table was required but it semmed it was in the case of has_many
and not has_and_belongs_to_many
statement).
Could you please help ?
I think this is a newby question but...
Thanks a lot,
Regards,
Luc
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于 HABTM,您需要一个名为categories_users 的连接表。使用此迁移:
For HABTM you need a join table called categories_users. Use this migration:
您的看法如何? Rails 的脚手架不支持多对多,因此您需要自己处理。
您的数据存储是什么样的?如果您使用的是 RDBMS,那么对于多对多关系,您通常需要一个联结表。大多数(所有?)SQL 数据库并不自然地处理多对多。
What does your view look like? Rails's scaffolding won't account for many-to-many, so you will need to handle it yourself.
What does your data store look like? If you are using a RDBMS, then for many to many relations you typically need a junction table. Many-to-many is not naturally handled by most (all?) SQL databases.