在 ruby on Rails 中处理多对多关系的最简洁方法是什么?
我有一个模型说用户,可以住在多个城镇(表示为另一个模型)。如果我创建一个新用户,我必须选择(并编辑)他们居住的不同城镇。由于时间限制,我经常会得到一个“比我想要的更黑客”的解决方案,涉及以下内容: http://blog.hasmanythrough.com/2006/4/20/many -多对多跳舞。
有什么受SO欢迎的好解决方案吗?
干杯...
树懒型
I have one model say user, that can live in multiple towns (represented as another model). If I create a new user I have to choose (and edit) the different towns that they live in. Due to time constraints, I often end up with a "hackyier than I would like" solution involving something like: http://blog.hasmanythrough.com/2006/4/20/many-to-many-dance-off.
Any nice solutions that are popular with SO?
cheers...
Slothishtype
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
has_and_belongs_to_many 关联就是针对这种情况而构建的。这是有关它的文档: http://apidock.com/rails/ActiveRecord/Associations /ClassMethods/has_and_belongs_to_many
否则,如果您需要存储有关关联本身的信息(城市表或用户表中不存在的字段,而是介于两者之间的字段),您可能只想设置两个并行的'has_many_through' 关联,并设置一个单独的 'user_city' 表。所以它将在用户表
和城市表中
然后,您可以调用:user.cities,并获取用户居住的城市列表。
The has_and_belongs_to_many association was built for this very situation. Here is the documentation on it: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many
Otherwise, if you need to store information abotu the association itself (fields that would not exist in the city table or the user table, but in between), you might just want to set up two, parallel 'has_many_through' associations, and set up a seperate 'user_city' table. So it would be in the user table
and in the cities table
Then, you CAN just call: user.cities, and get a list of the cities the user lives in.