Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a conditional active record query that checks to see if a relationship of type X exists (.count > 0) where attribute x and attribute y match specific input or if they match when attribute x and attribute y are switched.

I currently use an || operator with two long active record queries to cover both situations.

def coach_of?(user)
  if UserRelation.where(relation_type: 'coach-student').where(user_id: > 0 || 
     UserRelation.where(relation_type: 'coach-student').where(user_id: > 0

Is there a more clever way to do this or is this kind of query acceptable?

share|improve this question

Some notes:

  • if boolean then true else false end -> boolean.

  • UserRelation.where(user_id: -> UserRelation.where(user_id:, with_user_id:

  • active_record_collection.count > 0 -> active_record_collection.exists?

  • I don't understand why you have to check both ways, a "coach - student" relationship looks unidirectional.

Anyway, if you set up the coach_students association, you may write something like this:

def coach_of?(user)
  coach_students.where(with_user_id: user).exists? || 
    user.coach_students.where(with_user_id: self).exists?
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.