Skip to main content

A long conditional active record query that seems like it could be solved in a more clever fashion

Source Link
Ecnalyr
  • 413
  • 3
  • 12

A long conditional active record query that seems like it could be solved in a more clever fashion

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?