Q:

Writing scope to complex multiple associations - Rails 4

I am having challenges writing a scope that displays live_socials created by users belonging to a category_managementgroup called client_group.
Social.rb
belongs_to :user
scope :live_socials, -> {where(['date >= ?', Date.current])}

CategoryManagementgroup.rb
has_many :users

User.rb
has_many :socials
belongs_to :category_managementgroup

the below scope displays all the socials for users in the category_managementgroup called client_group:
users.joins(:socials, :category_managementgroup).client_group.flat_map(&:socials)

i am unsure how to extend the scope to display the live_socials
  (socials that have not expired). i tried the below but no success:

users.joins(:socials, :category_managementgroup).client_group.flat_map(&:socials).live_socials

i get the below error:

2.3.0 :264 > ap users.joins(:socials, :category_managementgroup).client_group.flat_map(&:socials).live_socials
  User Load (0.5ms)  SELECT "users".* FROM "users" INNER JOIN "socials" ON "socials"."user_id" = "users"."id" INNER JOIN "category_managementgroups" ON "category_managementgroups"."id" = "users"."category_managementgroup_id" WHERE "category_managementgroups"."name" = 'Client Group'
  Social Load (0.1ms)  SELECT "socials".* FROM "socials" WHERE "socials"."user_id" = ?  [["user_id", 10]]
NoMethodError: undefined method `live_socials' for #<Array:0x007ff2f9834570>

A:

Try applying live_socials scope before flat_map and add below scope to User model 
scope :live_socials, -> { joins(:socials).where(['socials.date >= ?', Date.current])}

