I have 3 models, UserActivity, User, and UserPhoto.

```
User
  has_many :user_photos, dependent: :destroy
  has_one :user_activity, dependent: :destroy
  has_one :subscription, dependent: :destroy

UserActivity
  belongs_to :user
  delegate :user_photos, to: :user

UserPhoto
    belongs_to :user  

```

I want to fetch all users that are "active" and have a subscription and order them by the last time they engaged in a "user activity" and order them according to the number of photos they have.

Currenty, I have: 

```
UserActivity.where(gender: "M")
            .joins(:user)
            .where("users.activation_state = 'active'")
            .order('user_activities.updated_at DESC')
            .includes([:user, user: [ :subscription ]])  

```

This will return all active users sorted by last activity update. 

I've tried adding query fragments such as ".joins(:user\_photo).order('user.user\_photos.length DESC')" which causes the above to choke. Can anyone point me in the right direction?

EDIT/Update: I used the counter cache as suggested by the below user and ended up with:

UserActivity.where(gender: "M")
 .joins(:user)
 .where("users.activation\_state = 'active'")
 .order('user\_activities.updated\_at DESC')
 .includes([:user, user: [ :subscription ]]).order('user\_photos\_count DESC')