1

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
neezer
  • 19,720
  • 33
  • 121
  • 220

1 Answers1

1

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

def buddies
  inverse_friends | friends
end

| is the union operator.

Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
  • I sometimes hate RoR for its simplicity. :) Thanks. – neezer Mar 18 '11 at 02:50
  • Aph, I spoke too soon... this gives me an array, not an AR::Relation. I want to be able to query on this method... (see edit above) – neezer Mar 18 '11 at 02:56
  • Wow, I really shouldn't code after nearly finishing a bottle of rather good `Terre del Negroamaro` (tasty!). I opted to stick with your union operator and adjusted my `buddies` method accordingly (see last edit above). Thanks again. – neezer Mar 18 '11 at 03:06