如何基于相关模型限制关联列表

时间:2016-04-20 13:14:22

标签: ruby-on-rails ruby drop-down-menu associations

我知道我应该知道这一点,但我似乎根本无法理解这一点,而且我仍然是发展新手......

所以我有四个模特......

约会

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"

我在这里遗漏了什么或有更简单的方法来查询吗?任何有关这方面的指导都会有所帮助。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

谢谢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。