2016-04-20 65 views
0

我知道,我應該知道這一點的關聯列表,但我似乎無法弄清楚在所有和我還是新發展......如何限制基於相關模型

所以我有四款機型...

約會

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" 

我在這裏丟失了什麼,或者有沒有更簡單的方法來查詢?任何這方面的指導都會有所幫助。

+0

你能否詳細解釋一下。 –

回答

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時出現錯誤。

0

如果您正在使用simple_form你應該創建collection_input這樣的:

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

這塊是它似乎沒有按預期拉動它: Location.where(location.profile_location.profile_id:@ profile.id) 是這種類型的過濾器基於活動個人資料? –

+0

哦,是的。我只是複製/粘貼你的查詢。這是錯誤的。你需要加入'profile_locations'。因此它會是:'Location.joins(:profile_location).where(profile_locations:{profile_id:@ profile.id})''。用正確的查詢更新答案 – ksarunas

相關問題