2015-11-02 72 views
0

我有這樣的聯想:職業 - >訂單 - >配置文件 - >位置的Rails:多個關聯查詢

Class Profession < ActiveRecord::Base 
    has_many: orders 
end 

Class Order < ActiveRecord::Base 
    has_one :profession 
    belongs_to :profile 
end 

Class Profile < ActiveRecord::Base 
    has_one :location 
    has_many :orders 
end 

Class Location < ActiveRecord::Base 
    belong_to :profile 
end 

,我需要找到一個職業,因爲他們位於location.city。 例如,我試試這個:

Profession.joins(:orders).where(orders: {profile: {location: {city: "Simferopol"}}}) 

這可能嗎? 謝謝。

回答

0

你可能使用通過考慮關聯:

class Profession < ActiveRecord::Base 
    has_many :orders 
    has_many :profiles, through: :orders 
end 

這可能使生活更輕鬆,讓您致電:

​​

這將返回所有配置對於一個給定的狀態。這對我來說似乎不太麻煩。由於您仍然需要到達與配置文件相關聯的位置,我確信存在更優化的解決方案,但我相信這種方法比擬議的更好:

Profession.joins(:orders).where(orders: {profile: {location: {city: "Simferopol"}}})