用户有很多:用户,或者我必须使用另一种方式来建立基于朋友的社交网络?
我正在 Rails 中创建一个小型社交网络,人们可以在其中互相添加为朋友。我创建了一个名为 'user'
的模型,其中包含电子邮件、带有密码盐的强 md5 哈希值等。
如何创建类似将另一个用户添加为好友的选项之类的内容?用户模型中是否可以有类似 has_many_and_belongs_to :user
的内容?所以一个用户有多个用户,并且属于多个用户。或者我应该使用另一种方式,例如添加具有 user1s_id:integer
和 user2s_id:integer
的友谊模型?
I'm creating a little social network in Rails, where people can add eachother as a friend. I have created a model called 'user'
, which contains, e-mail, strong md5 hash with salt of password etc.
How do I create something like an option to add another user as a friend? Is it possible to have something like has_many_and_belongs_to :user
in the user model? So a user has many users and belongs to many users. Or should I use another way, like adding a friendship model which has user1s_id:integer
and user2s_id:integer
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
本质上,您需要一个将用户连接到用户的连接模型。但您必须对 Rails 使用更具描述性的术语。
Twitter 不使用 Rails,但以下是使用 Twitter 术语在 Rails 中进行用户关联的方式。注意:Twitter 不要求双向关注(即仅仅因为一个用户关注另一个用户,并不意味着第二个用户关注第一个)
强制双向友谊(就像 Facebook 强制我不能与你成为朋友,除非你是以下用户的朋友 )我)将需要更多的工作。您需要使用回调来管理相互条目,或者使用自定义查找器 SQL。使用自定义查找器 SQL 意味着 ActiveRecord 可能无法为您管理关联。
Essentially you want a join model that joins users to users. But you'll have to use more descriptive terms for Rails.
Twitter doesn't use Rails, but here's how their user associations might work in Rails using Twitter's terminology. Note: Twitter doesn't require bidirectional following (ie just because a user follows another, doesn't mean that second user follows the first)
Forced bidirectional friendship (like Facebook enforces that I cannot be friends with you, unless you are a friends with me) will take a little more work. You will either need to manage reciprocal entries with callbacks, or use custom finder SQL. Using custom finder SQL means that ActiveRecord probably won't be able to manage associations for you.
我建议一个用户有很多关系,这样你将来就可以自由地添加新类型的关系。
因此,您从“一个用户到另一个用户”关系表(至少只有两个 ID)开始,然后将来您可以添加一个“一个用户到一个组”关系表(当然,一旦您创建了组!)
I would suggest that a user has many relationships, this would leave you free to add new types of relationships in the future.
So you start with a "one user to another user" relationship table (minimally, just two IDs) and then in the future you could add a "one user to a group" relationship table (once you've created groups of course!)
我建议使用友谊模型,因为从数据库角度来说,无论哪种方式,您都需要一个连接表,但是明确该表将允许您存储有关关系的更多详细信息(例如“朋友”或“家人”、添加日期、 ...)
I'd suggest using the friendship model because db-wise you'll need a join table either way, but making that table explicit will allow you to store more details about the relationship (e.g. "friend" or "family", date added, ...)