在 Rails 中使用相同数据类型创建多个关系
我想做的是这样的:
例如,我有数据类型“用户”和“文章”。我希望在两者之间建立关系,但方式不只一种。
例如,我想让用户“喜欢”或“添加书签”一篇文章。因此,我需要在数据库中有两种关系,一种用于用户喜欢该文章的关系,另一种用于用户添加书签的关系,因此创建一个“user_article”表是不够的,对吗?
这样做的最佳方法是什么?
What I am trying to do is kind of like this:
I have datatypes "user" and "article" for instance. I want to have relationships between these two, but in more than one way.
So for instance, I'd like to let a user "like" or "bookmark" an article. So I need to have two relations in the database, one for users liking the article, and one for users bookmarking, so making a "user_article" table for instance won't be sufficient, correct?
What is the best way of going about doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所描述的是“数据模型”而不是“数据类型”。数据类型 = 字符串、整数等。如果它是 Active Record 对象,则它是数据模型或更具体地说是 Active Record 模型。
Eimantas 指出,您正在描述 2 个“has_many”关系,但不是他帖子中所写的“have_many”。在他的示例中,书签称为连接模型。请记住,您可以将其他内容放入连接模型中,并使用其中的关系来完成任务。假设您想要一个书签订单或最喜欢的排名 - 连接模型就是实现此目的的理想场所。
精简示例:
了解基础知识后需要注意的事项:
计数器缓存 - 如果您进行计数,它们就是您的朋友。
仅使用这两个连接模型可能比现在尝试深入研究多态性更容易、更清晰。启动并运行之后,您就可以探索下一步了。
What you are describing are "Data Models" not "Data Types". Data types = String, integer etc. If it is a Active Record Object it's a Data Model or a Active Record Model more specifically.
Eimantas pointed out you are describing a 2 "has_many" relationships but not "have_many" as written in his post. In his example the bookmarkings is called a join model. Remember you can place other things in the join model and use the relationships there to accomplish things. Say you want to have a bookmark order or a favorite rank- the join model is the idea spot for this.
Stripped down example:
Things to look at after getting the basics down:
Counter caches - if you are doing counts they are your friend.
It is likely way easier and cleaner to just use these 2 join models rather than try to dive into polymorphism right now. After you get that up and running you could explore that next.
我建议使用具有
bookmarking_type
的Bookmarking
模型(请注意,type
是为 RoR 保留的)。然后你可以has_many :bookmarkings
和has_many :liked_articles, :through =>; :bookmarkings
和has_many :bookmarks, :through => :书签
。当然,您应该添加条件或只是将 SQL 连接到这些关联中,但一切都应该很好。我相信甚至有一个插件,只是不记得自动取款机的名字了。I'd suggest
Bookmarking
model that havebookmarking_type
(note thattype
is reserved for RoR). Then you couldhas_many :bookmarkings
andhas_many :liked_articles, :through => :bookmarkings
andhas_many :bookmarks, :through => :bookmarkings
. Of course you should add conditions or just join SQL to these assocations, but all should be good. I do believe there's even plugin for that, just can't recall the name atm.