Rails Filtered Associations with HABTM

Hi all,

I have a interesting association I am trying design and can’t seem to come up with the right way to do it, so thought I would ask for help.

Essentially, we have four models that matter: Family, ActivityTemplate, Device and DeviceType. A Family has many Devices, Device belongs_to a DeviceType, and ActivityTemplates has_and_belongs_to_many DeviceTypes (think: these device types are supported in this activity).

What I am trying to do is get the list of FamilyActivity_instance.devices that are available. Or, stated another way, we know what DeviceTypes are capable of being used in a FamilyActivity, so I need the subset of Family.devices that match those DeviceTypes.

Here are the models just for reference:

class Family < ActiveRecord::Base
  has_many :devices
end

class Device < ActiveRecord::Base
  belongs_to :device_type
  belongs_to :family
end

class FamilyActivity < ActiveRecord::Base
  belongs_to :family
  has_and_belongs_to_many :device_types
  belongs_to :activity_template
end

class ActivityTemplate < ActiveRecord::Base
  has_and_belongs_to_many :device_types
  has_many :family_activities, dependent: :nullify
end