如何根据相关模型限制关联列表

How to limit an association list based on a related model

我知道我应该知道这一点,但我似乎根本无法弄清楚,而且我还是开发新手...

所以我有四个模型...

约会

class Appointment < ActiveRecord::Base
    belongs_to :user
    belongs_to :profile
    belongs_to :location
end

个人资料

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

和地点

class Location < ActiveRecord::Base

    has_many :profile_locations
    has_many :profiles, through: :profile_locations

    has_many :appointments

end

在创建约会页面上,我已经有一个关联的个人资料记录在案。我的 simple_form 上还有一个关联字段,用于我希望能够根据与个人资料相关的位置分配给约会的位置..

我正在尝试类似的操作,但似乎无法正常工作。

%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"

我是不是遗漏了什么,或者有更简单的查询方法吗?关于这些的任何指导都会有所帮助。

如果您正在使用 simple_form,您应该像这样创建 collection_input

%td= f.input :location, collection: Location.joins(:profile_location).where(profile_locations: { profile_id: @profile.id })

谢谢 ksarunas....我需要一个小的调整,但我做到了 运行!

%td= f.association :location, :as => :collection_select, collection: Location.includes(:profile_locations).where(profile_locations: { profile_id: @appointment.profile_id })

尝试拉入 @profile.id 时出错,不得不在两个地方将 profile_locationS 复数化。