I’m trying to create an app where users (‘current_user’) rate the compatibility between two other users (‘user1’ and ‘user2’). They can rate compatibility either positively or negatively: rating two users “compatible” creates two resources of the same class (a ‘positive_connection’ and an ‘inverse_positive_connection’ – for bidirectionality), and rating them “incompatible” also creates two resources(‘negative_connection’ and ‘inverse_negative_connection’). So there are models for positive_connection, negative_connection and user.
Each rating resource belongs_to the user who created it, but also to the users connected by it. It’s important to have both positive and negative ratings.
This is my problem: on every user (@user) page I want to display separate lists of:
-
users that are
overall_positively_connected_to(@user)(i.e.positive_connections.count > negative_ratings.count), and -
users that are
overall_negatively_connected_to(@user)(i.e.negative_connections.count > positive_ratings.count).
What I can’t seem to do is write a class method that pulls out only those users who are net-rated “compatible” or “incompatible”
From reading Michael Hartl’s rails tutorial (I’m completely new to all this), I think I need to write something like this in the User model:
class User < ActiveRecord::Base
def self.that_are_compatible_with
User.overall_positively_connected_to(user)
end
.
.
.
EDIT
Starting with absolutely no knowledge of SQL queries at all, I wrote these two class methods for finding users that are negatively and positively connected to @user (respectively):
.
.
.
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
But that’s not much help. What I need is a method that gets the users overall_positively_connected_to(user). I presume the method would involve two joins, and go something like this:
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
But here I get completely stuck: it’s obviously not right. I can’t find other examples like it anywhere…
Any help whatsoever on this would be great as I have no clue when it comes to SQL queries. Let me know if more code needed. Thanks in advance!
Having struggled with this for a few days, I decided that the best way of going about solving the problem is probably to change the models round – either by adding an additional “connection” model and having users vote positively or negatively on each connection, or by slimming down to a single “connection” model where the positive or negative character of each connection is marked by a +1/-1.
A couple of alternatives can be found in answers to this question.