如何在模型中嵌套模型
想象一下我有两个模型
Film
-name
-description
-duration
-year_made
-rating
-actors
Actor
-name
-d_o_b
-biography
-films
演员嵌套在电影中,反之亦然。
如何在 Ruby 模型中表示这种关系?实际上,我会有第三个表将 actor_id
与 film_id
进行映射。
在向电影添加细节时,我希望能够动态创建一个演员(如果演员不存在,请使用提供的名称创建一个新演员)
提前谢谢您。
添加:
刚刚找到了类似问题。
Imagine I have two models
Film
-name
-description
-duration
-year_made
-rating
-actors
Actor
-name
-d_o_b
-biography
-films
Actors are nested in a Film and vice versa.
How do I represent this relationship in my Ruby models? Realistically I would have a third table mapping actor_id
with film_id
.
Whilst adding details to a film I would like to be able to create an actor on the fly(if an actor does not exist create a new one with the name supplied)
Thank you in advance.
ADDITION:
Just found a link to a similar question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在查看两个表之间的“拥有”和“属于多个”(HABTM) 关系。
在 Rails 指南中阅读有关 HABTM 关系的信息:http://edgeguides.rubyonrails.org /association_basics.html#has_and_belongs_to_many-association-reference
首先你需要生成一个迁移,如下所示:
然后在模型中指定:
这将允许您为这种类型的关系使用所有附加的 Rails 方法。要在表单中使用它,您可以遵循 RailsCast 17:HABTM 复选框 - 尽管它很旧,它应该仍然适用。或者,您可以使用 Simple Form 之类的 gem 轻松生成关联,如下所示:
You're looking at a Has and Belongs to Many (HABTM) relationship between the two tables.
Read about HABTM relationship in the Rails guides here: http://edgeguides.rubyonrails.org/association_basics.html#has_and_belongs_to_many-association-reference
First you'll need to generate a migration which will look something like this:
and then specify in your models:
This will allow you to use all of the additional Rails methods for this type of relationship. To use this in a form, you could follow RailsCast 17: HABTM Checkboxes - though it's old, it should still apply. Alternatively, you can use a gem like Simple Form to easily generate the associations for you like so: