Rubioli Rubioli - 7 months ago 11
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|
%p= user.name
%p= user.city.name


Instead of
any?
, 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

Answer

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|
    %p= user.name
    %p= user.city.name