5
\$\begingroup\$

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: self.id).where(with_user_id: user.id).count > 0 || 
 UserRelation.where(relation_type: 'coach-student').where(user_id: user.id).where(with_user_id: self.id).count > 0
 true
 else
 false
 end
end

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

JaDogg
4,5513 gold badges29 silver badges65 bronze badges
asked Aug 19, 2014 at 13:44
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Some notes:

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

  • UserRelation.where(user_id: self.id).where(with_user_id: user.id) -> UserRelation.where(user_id: self.id, with_user_id: 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?
end
answered Aug 19, 2014 at 15:26
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.