Reputation: 680
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
Upvotes: 0
Views: 160
Reputation: 101811
Generally you should avoid doing database queries in the view - A better solution is to do it in the controller or in the model:
class User < ActiveRecord::Base
# ...
def self.by_group_and_city(friend_group, city, threshold: 2)
scope = User.where(friend_group: friend_group, city: city)
# if you want only if exactly two records match then use ==
scope.size >= threshold ? scope : User.none
end
end
We return User.none
instead of nil if there are no matching records - that way you can safely call methods like .each
on the empty relation object.
- User.by_group_and_city(0, 2).each do |u|
%p= user.name
%p= user.city.name
Better yet would be let the controller do the querying:
def index
@nearby_users = User.by_group_and_city(0, 2)
# ...
end
- @nearby_users.each do |u|
%p= user.name
%p= user.city.name
Upvotes: 2
Reputation: 16507
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
Upvotes: 0