我正在尝试创建一个应用程序,其中用户('current_user')对其他两个用户('user1'和'user2')之间的兼容性进行评分。他们可以对兼容性进行正面或负面评价:给两个用户评分“兼容”会创建两个相同类别的资源(一个“positive_connection”和一个“inverse_positive_connection” - 用于双向性),并且给他们评分“不兼容”也会创建两个资源('negative_connection '和'inverse_negative_connection')。所以有positive_connection、negative_connection和user的模型。
每个评级资源都属于创建它的用户,也属于它连接的用户。拥有正面和负面的评级很重要。
这是我的问题:在每个用户(@user
)页面上,我想显示单独的列表:
是
overall_positively_connected_to(@user)
(即positive_connections.count > negative_ratings.count
)的用户,并且是
overall_negatively_connected_to(@user)
(即negative_connections.count > positive_ratings.count
)的用户。
我似乎无法做的是编写一个类方法,只提取那些被网络评为“兼容”或“不兼容”的用户
通过阅读 Michael Hartl 的 rails 教程(我对这一切完全陌生),我认为我需要在 User 模型中编写类似这样的内容:
class User < ActiveRecord::Base
def self.that_are_compatible_with
User.overall_positively_connected_to(user)
end
.
.
.
编辑
从完全不了解 SQL 查询开始,我编写了这两个类方法来查找与@user 负相关和正相关的用户(分别):
.
.
.
def self.with_neg_connections_to(user)
joins(:negative_connections).
where(:negative_connections => {:user_a_id => user})
end
def self.with_pos_connections_to(user)
joins(:positive_connections).
where(:positive_connections => {:user_a_id => user})
end
但这并没有多大帮助。我需要的是一种获取用户的方法overall_positively_connected_to(user)
。我认为该方法将涉及两个连接,并且是这样的:
def self.overall_positively_connected_to(user)
joins(:positive_connections).joins(:negative_connections).
where((:negative_connections => {:user_a_id => user}).count > (:positive_connections => {:user_a_id => user}).count)
end
但是在这里我完全卡住了:这显然是不对的。我在任何地方都找不到其他类似的例子......
任何关于这方面的帮助都会很棒,因为我对 SQL 查询一无所知。如果需要更多代码,请告诉我。提前致谢!