Q:

How to limit an association list based on a related model

I know that I should know this, but I cannot seem to figure it out at all and I'm still new to development...
So I have four models...
Appointments
class Appointment < ActiveRecord::Base
    belongs_to :user
    belongs_to :profile
    belongs_to :location
end

Profiles
class Profile < ActiveRecord::Base

    belongs_to :user
    has_many :appointments

    has_many :profile_locations
    has_many :locations, through: :profile_locations
    accepts_nested_attributes_for :profile_locations, reject_if: :all_blank, allow_destroy: true
    accepts_nested_attributes_for :locations, reject_if: :all_blank, allow_destroy: true

end

profile_locations
class ProfileLocation < ActiveRecord::Base

    belongs_to :profile
    belongs_to :location
    belongs_to :location_type

    accepts_nested_attributes_for :location

end

and locations
class Location < ActiveRecord::Base

    has_many :profile_locations
    has_many :profiles, through: :profile_locations

    has_many :appointments

end

On the create appointments page, I already have an associated profile on the record.  I also have an association field on my simple_form for locations that I want to be able to assign to the appointment based on those tied to the profile..
I was trying something like this, but cannot seem to getting working.
%td= f.association :location, :as => :collection_select, collection: Location.where( location.profile_location.profile_id: @profile.id ), label_method: :address_1, value_method: :id, include_blank: false, :input_html => {:class => "input-small"}, :label => "Select The Location"

Am I missing something here or is there an easier way to query this?  Any guidance on any of this would be helpful.

A:

Thanks ksarunas....   I needed a minor tweak, but got it running!
%td= f.association :location, :as => :collection_select, collection: Location.includes(:profile_locations).where(profile_locations: { profile_id: @appointment.profile_id })

Was getting an error trying to pull in the @profile.id and had to pluralize the profile_locationS in both places.

