活动记录,其中外键可以是两列中的任何一个
我有一个用户模型。
我有一个朋友模型,其中包含 informe_id 和 Inviter_id 列以及状态。状态用作好友请求是否已被接受的标志。 Inviter_id是发送好友请求的用户id,inviter_id是接收好友请求的用户。请查看内嵌评论。
class User < ActiveRecord::Base
has_many :friends // now i want to search all the friends with accepted friend request. (sent or received both.)
has_many :pending_friend_requests,:class_name => "Friend", :foreign_key=>"invitee_id", :conditions => {:status => 0}
end
class Friend < ActiveRecord::Base
end
问题是如何获取所有已接受朋友请求的朋友..发送或接收,因为有两个外部列。 informee_id 或 Inviter_id
I have a User Model.
I have a Friend Model with columns invitee_id and Inviter_id and status. Status is used as flag whether friend request has been accepted or not. Inviter_id is the id of the user who sending the friend request and invitee_id is the user who is receiving the friend request.Please check inline comment.
class User < ActiveRecord::Base
has_many :friends // now i want to search all the friends with accepted friend request. (sent or received both.)
has_many :pending_friend_requests,:class_name => "Friend", :foreign_key=>"invitee_id", :conditions => {:status => 0}
end
class Friend < ActiveRecord::Base
end
Question is how to fetch all the friend with accepted friend requests.. sent or received as there are two foreign columns. invitee_id or Inviter_id
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我的问题正确,那么这个截屏视频就是您所需要的。
更新
虽然你说你不需要,但我认为你确实需要一种自引用的多对多关系。
您可以创建一个命名范围,而不是为待处理的请求建立关联。之后,您可以通过
User.find(params[:id]).friends.accepted
获取您邀请的所有好友。我不明白的是你是否希望 user.friends 检索邀请我的人和我邀请的人,或者只检索其中之一。
由于您的命名(邀请者和被邀请者),我认为这是第二种情况。它包含在截屏视频中。这是通过创建额外的反向关联来完成的(Ryan 在最后谈到了这一点)。
但如果是第一个,最简单的解决方案是为每个邀请者-受邀者对制作两行。您可以使用这个 gem 来简化事情,但它的作用与我所说的相同。
如果没有帮助,请尝试具体说明您的问题。
If I got your question right, this screencast is what you need.
Updated
Altough you say you don't, I think, you do need a self-referential many-to-many relation.
Instead of making an associations for pending requests, you could make a named scope. And after that, you could get all the friends you invited by
User.find(params[:id]).friends.accepted
.What I can't understand is whether you want user.friends to retrieve both the ones who invited me and the ones invited by me OR only one of these.
Because of your namings (inviter and invitee) I suppose it is the second case. An it is covered in the screencast. It is done by creating additional inverted association (Ryan talks about that in the end).
But if it's the first one, the easiest solution would be to make two rows for each inviter-invitee pair. You could use this gem to simplify things, but it acts the same way I told.
If it doesn't help, try to specify your question.
has_many
设置关系。使用scope
作为条件。然而,由于模型和列的设置方式,这很令人困惑。如果我这样做,我会做类似的事情:
The
has_many
sets up the relations. Usescope
for conditions.However, this is way to confusing because of the way that the models and columns are setup. If I were doing this I would do something like: