关于 Rails 中正确关联的问题
就以这种情况为例。
您有 3 个模型:
- 诗人 - 代表一首诗的作者
- 诗歌 - 代表诗人写的一首诗
- 印刷 - 代表包含诗人诗歌的任何类型的印刷出版物。
诗人和诗歌一目了然:
- 诗人
has_many
诗歌 - 诗歌
belongs_to
诗人
在处理印刷模型时,这让我感到困惑。
在这种情况下,印刷品在某种意义上既属于诗人又属于诗歌。你可以说一位诗人有很多印刷品或一首诗有很多印刷品,这是有道理的,但走相反的路线是很棘手的……
如果一些杂志或书籍印刷了一位诗人的 5 首诗,情况又如何呢?或者,其中一首诗发表在 10 种不同的杂志上?
印刷本身似乎“属于许多”诗歌或诗人。我知道这是错误的,但我只是想阐明这一点。
所以可以回答的问题是这样的: 您将如何建立这些关系?具体来说,模型和数据库表是什么样子以及如何使用它们来访问关联数据?
谢谢你!
Take for example this situation.
You have 3 models:
- Poet - Represents the author of a poem
- Poem - Represents a poem written by a Poet
- Printing - Represents a printed publication of any sort containing the Poet's Poem.
Right off the bat poet and poem are obvious:
- Poet
has_many
poems - Poem
belongs_to
poet
It becomes confusing for me when dealing with the Printing model.
In this case a Printing, in some sense, belongs to both the poet and poem. You could say a poet has_many printings or a poem has_many printings which makes sense but going the inverse route is tricky...
What about a situation where some magazine or book printed 5 poems from one poet? OR, one of the poems is published in 10 different magazines?
It almost seems as if the Printing itself "belongs to many" poems or poets. I know this is wrong, but i'm just trying to articulate the point.
So the answerable question is this:
How would you set up these relationships? Specifically, what would the model and database table look like AND how would you use them to access associated data?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请记住,如果您有一位诗人有很多诗歌,并且印刷品也有很多诗歌,那么您总是可以找到这位诗人。
Poet.poems.first.printings 将返回诗人第一首诗的所有印刷品
,或者您可以执行 Printing.poems.first.poet 这样您就可以获得印刷品中第一首诗的诗人。
我会这样设置
因为您使用的是 has_and_belogs_to_many 关联,所以您需要一个连接表,对于诗歌和印刷品,
您将进行如下所示的迁移
其他表非常简单
Remeber if you have a poet that has many poems and printing that has many poems as well you can alway get the poet.
Poet.poems.first.printings would return all the printings of the poets first poem
or you could do Printing.poems.first.poet This way you could get the poet of the first poem in the printing.
I would set it up like this
Because you are using a has_and_belogs_to_many association you need a join table, for poems and printings
you would have migration that looks like this
The other tables are pretty easy