has_many :through 关联是否需要连接表?
我之前只创建了一个 has_and_belongs_to_many 关联,它与 has_many :through 不同。对于 has_many :through 关联,我需要连接表吗?实际的协会是如何运作的?我需要索引吗?我找不到这方面的精彩教程,有什么建议吗?
I've only created a has_and_belongs_to_many association before and it is different from has_many :through. For a has_many :through association, do I need a join table? How does the actual association work? Do I need an index? I can't find a great tutorial on this, any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您需要连接表。
这显示了如何: http://railscasts.com/episodes/47-two-多对多
这也可能有帮助; has_many :through questions
顺便说一句,如果您需要按条件搜索,这会有所帮助:有许多与条件的关联
也是一个很好的代码示例编辑连接表的嵌套属性 带有 has_many 的 Rails 嵌套形式:通过,如何编辑连接模型的属性?。
所有这些都是您可能会发现自己想做的事情:)
索引是可选的,并且也因数据库而异。 mySQL 过去一次只支持 1 个。不确定这是否已经改变。
Yes you need the join table.
This shows how: http://railscasts.com/episodes/47-two-many-to-many
This may also be helpful; has_many :through questions
By the way if you need to search with condition this will help: Has many through associations with conditions
Also a great example with code of editing the nested attributes of the join table at Rails nested form with has_many :through, how to edit attributes of join model?.
All these are sorts of things you might find yourself wanting to do :)
Index are optional and also vary by db. mySQL used to only support 1 at a time. Not sure if that has changed.
这取决于您想要如何使用
has_many :through
关系。有两种不同的情况(在关系指南中命名,您需要连接表,而对于第二个段落,则不需要索引。
It depends on how you want to use the
has_many :through
relation. There are two different cases (named in the guide to relationsFor the first one, you need the join table, you don't need the index. For the second one, you need none of them.