ruby on rails - How can i count total number of user registerd with their respective roles? -
i have buying , selling rails app, users have 2 roles buyers , sellers want show records on homepage how many buyers there on site , how many sellers on site. using user.count shows user registered on site
my seeds.rb
['buyer', 'seller'].each |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
using role object count role:
role = role.find_by(name: 'buyer') user.where(role: role).count or can include roles table , query through users:
user.includes(:role).where(role: {name: 'buyer'}).count
Comments
Post a Comment