getting the count of another table values in existing query Rails

150 views Asked by At

Currently I am doing this to get data from my tables as

cameras = Camera.joins("left JOIN users on cameras.owner_id = users.id")
                .joins("left JOIN vendor_models vm on cameras.model_id = vm.id")
                .joins("left JOIN vendors v on vm.vendor_id = v.id")
                .where(condition).order(sorting(col_for_order, order_for)).decorate

And this generates such query as

SELECT "cameras".* FROM "cameras" left JOIN users on cameras.owner_id = users.id left JOIN vendor_models vm on cameras.model_id = vm.id left JOIN vendors v on vm.vendor_id = v.id

I have an other table as camera_shares on which I have relation of camera's table as there is a camera_id which is present in camera_shares table as well, in each camera_shares there is an camera_id which tell us that the share is for which camera, I want to calculate the count of camera_shares, For example if there is a camera with id 12 and there are also 20 camera_shares with camera_id = 12 then I want to count the total of it. I want to do that in Rails query as I have shown above? How is that possible to do?

1

There are 1 answers

3
EJAg On

Seems rather straightforward. Suppose you want to find the number of camera_shares for @camera:

CameraShare.where(camera: @camera).count