Rails 3 中的高级友谊模型和查询
我有友谊模型,对于每一个新的友谊,我都会创建两个新记录:
- User1 和 Friend1
- Friend1 和 User1
我可以检索所有标准人员,例如:朋友,友谊,pending_friends ...当我尝试获得共同朋友时,情况变得复杂,朋友的朋友...
现在为了获得共同的友谊,我使用类似的东西:
has_many :common_friendships, :class_name => 'Friendship', :conditions=>'friendships.user_id = #{self.id}' do
def common_with(friend)
joins("inner join friendships fl2 on friendships.friend_id = fl2.user_id").where("fl2.friend_id = #{friend.id}")
end
end
我也可以使用 finder_sql
进行完整查询,例如:
select distinct *
from friendships fl1
inner join friendships fl2 on fl1.friend_id = fl2.user_id
where fl1.user_id = 1 and fl2.friend_id = 2
如何在 Rails 3 中以优雅的方式做到这一点?
I have friendship model, and for every new friendship, I create two new records:
- User1 and Friend1
- Friend1 and User1
I can retrieve all standard staffs like: friends, friendships, pending_friends... The situation becomes complicated when I try to get common friends, friends of friends...
For now to get common friendships, I use something like:
has_many :common_friendships, :class_name => 'Friendship', :conditions=>'friendships.user_id = #{self.id}' do
def common_with(friend)
joins("inner join friendships fl2 on friendships.friend_id = fl2.user_id").where("fl2.friend_id = #{friend.id}")
end
end
Also I can use full query with finder_sql
like:
select distinct *
from friendships fl1
inner join friendships fl2 on fl1.friend_id = fl2.user_id
where fl1.user_id = 1 and fl2.friend_id = 2
How can I do that in an elegant way in Rails 3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看此问题的答案:
如何在 Rails 3 中为社交网络应用程序实现友谊模型?
Check out the answer on this question:
How to Implement a Friendship Model in Rails 3 for a Social Networking Application?