1

I'm not sure this is even possible, but let's see if one of you comes up with a solution. This is more or less about code quality in terms of readability and not an actual problem because I already have a solution. I have a friendship model and a user model. The friendship model is used to model friendships between two users:

class Friendship

  def self.requested(user)
    where(:user_id => user).where(:status => 'requested')
  end

  def self.pending(user)
    where(:user_id => user).where(:status => 'pending')
  end

  def self.accepted(user)
    where(:user_id => user).where(:status => 'accepted')
  end

  # ...

end

class User
   has_many :friendships

   # ...
end

Is it somehow possible to call the requested, pending or accepted scope through the user model without providing an argument?

a_user.friendships.pending # this does not work, is there a way to get it working?

a_user.friendships.pending(a_user) # works of course!
tshepang
  • 12,111
  • 21
  • 91
  • 136
t6d
  • 2,595
  • 3
  • 26
  • 42

1 Answers1

4

I think this should work if you take the argument off. Calling pending off of the user object like this should already scope friendships to the appropriate user. Define the method like this:

def self.pending
  where(:status => 'pending')
end

And call:

a_user.friendships.pending

Check the logs for the generated query if you're not sure it's working.

If you still want to call it by passing an argument I'd name that method Friendship.pending_for(user).

Mat Schaffer
  • 1,634
  • 1
  • 15
  • 24
  • Awesome! I should have tried that first. Sometimes, I underestimate the magic of Active Record. Works like a charm. Thanks a lot. – t6d Apr 11 '11 at 22:17
  • By the way, instead of defining a method, I now simply used `scope :pending, where(:status => 'pending')`. – t6d Apr 11 '11 at 22:18
  • Be a little careful with that. Doing the 'scope' way causes (or used to cause) Arel to look up the status column at class load time. So if you introduced the column in a migration that hadn't yet run, stuff breaks. lambda scopes or class methods seem to be the best way to go to avoid this. – Mat Schaffer Apr 24 '11 at 02:25