Ahmed Reza February 2016

How can i count total number of user registerd with their respective roles?

I have a buying and selling rails app, where users have two roles buyers and sellers i want to show records on my homepage that how many buyers are there on the site and how many sellers on the site. but by using the User.count it shows all the user registered on my site

My seeds.rb

['buyer', 'seller'].each do |role|
  Role.find_or_create_by({name: role})
end

Models

Role.rb

class Role < ActiveRecord::Base
    has_many :users
end

Users.rb

   belongs_to :role
   def has_role? test_role
       role.id == 2
       role.id == 1
   end

Answers


infused February 2016

Using a role object to count by role:

role = Role.find_by(name: 'buyer')
User.where(role: role).count

Or you can include the roles table and query through users:

User.includes(:role).where(role: {name: 'buyer'}).count

Post Status

Asked in February 2016
Viewed 2,621 times
Voted 13
Answered 1 times

Search




Leave an answer