Rubioli Rubioli - 10 months ago 27
Ruby Question

Ruby on Rail - Check if at least 2 records with my condition exsist

In my application, I want to show db records only if 2 records with my/same conditions exists?

What is the most efficient way of checking it?

Here is my code:

- if @users.where(friend_group: 0).where(city_id: 2).any?
- @users.where(user_group: 0).where(city_id: 2).each do |user|

Instead of
, I want to check if when only 2 records with same conditions exist, it can show them.

I have tried
- if @users.where(friend_group: 0).where(city_id: 2).exist?(2)
, with no luck.

ps: I am using rails 4.2


Just use active record relation's #count, and range indexation as follows:

- rela = @users.where(friend_group: 0).where(city_id: 2)
- if rela.count > 1
  - rela[0..1].each do |user|