Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method for greater than one?

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.

like image 685
Dodinas Avatar asked May 17 '26 03:05

Dodinas


2 Answers

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 true if the collection has more than one record. Equivalent to collection.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.

like image 148
Andrew Marshall Avatar answered May 20 '26 01:05

Andrew Marshall


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:

  1. Add a column groups_count to users table

    add_column :users, :groups_count, :integer, default: 0

  2. 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

like image 23
Muntasim Avatar answered May 20 '26 00:05

Muntasim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!