victorhazbun
victorhazbun

Reputation: 841

Rails group count complex associations

I want to group and count through my has_one association called company_friend this table has a column called name.

I'm using Rails 5.

class Appointment
  belongs_to :company_friendship, touch: true
  has_one :company_friend, through: :company_friendship
end

class CompanyFriendship < ApplicationRecord
  belongs_to :company, touch: true
  belongs_to :company_friend, touch: true, class_name: "Company"
end

class Company < ApplicationRecord
  has_many :company_friendships, autosave: true
  has_many :company_friends, through: :company_friendships, autosave: true
end

I want to group using the company_fiend.name column

The expected output should be like this:

{"nestle" => 10, "cocacola" => 20, "los pollos hermanos" => 50}

I'm doing:

Appointment.joins(:company_friend).group("company_friends.name").count

But I get:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "company_friends"
LINE 1: SELECT COUNT(*) AS count_all, company_friends.name AS compan...

Upvotes: 2

Views: 1357

Answers (1)

victorhazbun
victorhazbun

Reputation: 841

This is what I needed:

Appointment.joins(:company_friend).group("companies.name").count

{"Barton Mines"=>772, ... }

Upvotes: 3

Related Questions