I have a query that I run in Rails:
me = User.find(1)
my_groups = me.groups
my_groups can return more than one row, potentially.
Is there a quick and dirty way to use a method to determine if my_groups or me.groups is greater than one?
Maybe something like my_groups.greater_than_one? If not, what would you recommend in determining if the query is return >1 row?
me.groups is essentially another table that is associated with User. It basically shows what "groups" a particular user belongs to.
There needn’t be a method for everything, you can simply compare against size:
me.groups.size > 1
However, ActiveRecord::Relation does have many? which will return true if there is more than one record. From the docs:
Returns
trueif the collection has more than one record. Equivalent tocollection.size > 1.class Person < ActiveRecord::Base has_many :pets end person.pets.count #=> 1 person.pets.many? #=> false person.pets << Pet.new(name: 'Snoopy') person.pets.count #=> 2 person.pets.many? #=> true
If you only cared about if there are any elements (i.e. >0) there’s any (which is also part of Ruby core’s Enumerable). But beware [nil, false].any? #=> false.
You can get this by:
if me.groups.count > 1 # or me.groups.size > 1 or me.groups.any?
'bla bla...'
else
....
end
But I do recommend to have counter cache in User class.
To do so:
Add a column groups_count to users table
add_column :users, :groups_count, :integer, default: 0
In Group model
belongs_to :user, counter_cache: true
Thus you can achieve your goal by:
if me.groups_count > 1
'bla bla...'
else
....
end
This will reduce the db query
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With