This should be a simple query, but I'm having problems getting the Rails syntax right. I'm using Rails 4.1.1 and Postgresql(9.3). I have a model User, and model Company. User has one company, and Company has many users. I'm trying to find all companies that have more than 5 users.
class Company < ActiveRecord::Base
has_many :users, dependent: :destroy
...
class User < ActiveRecord::Base
belongs_to :company
...
Question is similar to this: Find all records which have a count of an association greater than zero
If I try similar solution as mentioned above:
Company.joins(:users).group("company.id").having("count(users.id)>5")
It gives me an error:
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "company"
LINE 1: ... "users"."company_id" = "companies"."id" GROUP BY company.id...
I've tried several different queries for getting the result, but I've failed to do so. I could use SQL, but it seems dumb as this should be doable easily with ActiveRecord.
Thanks for all the replies :)