Question

How would I write this query using MetaWhere (in Rails 3)?

SELECT "users".* FROM "users" 
INNER JOIN "friendships" friends 
   ON "users"."id" = friends."friend_id" 
INNER JOIN "friendships" inverse_friends 
   ON "users"."id" = inverse_friends."user_id" 
WHERE friends."user_id" = 4 
   AND friends."status" = 't' 
   AND inverse_friends."friend_id" = 4 
   AND inverse_friends."status" = 't'

I'm trying to add a method on myUser class called buddies that will return both friends and inverse_friends from this Railscast on self-referential association.

I'd appreciate any help!


EDIT: I want to be able to query on the returned set, such that I can do:

def is_a_buddy_of?(user)
  not self.buddies.where(:friend_id >> user.id).empty?
end

SOLUTION: Nevermind that last edit, I just modified my is_a_buddy_of?(user) method to this, using the | operator on my existing associations:

def is_a_buddy_of?(user)
  status = false
  self.buddies.map do |buddy|
    status = true if buddy.id == user.id
  end
  status
end
Was it helpful?

Solution

why don't you just do the following in your User model?:

def buddies
  inverse_friends | friends
end

| is the union operator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top