-1
我很難包裝我的頭如何構建此查詢。我不確定是否應該嘗試創建一堆範圍並嘗試鏈接它們。或者我把它放到類方法中?或者我會做兩個組合嗎?如果有人能給我一個簡短的例子,它會阻止我跳出窗口,我已經爲此工作了一個多星期了。複雜的ActiveRecord查詢
class CensusDetail < ActiveRecord::Base
belongs_to :apartment
belongs_to :resident
end
class Apartment < ActiveRecord::Base
belongs_to :apartment_type
has_many :census_details
has_many :residents, :through => :census_details
end
class ApartmentType < ActiveRecord::Base
has_many :apartments
end
class Resident < ActiveRecord::Base
has_many :census_details
has_many :apartments, :through => :census_details
end
apartment.rent_ready = boolean value if apartment is ready
apartment_type.occupany = the number of allowed occupants in an apartment
census_detail.status = either "past", "present", or "new"
census_detail.moveout_date = date time resident is scheduled to move out
我需要建立一個查詢,執行以下操作:
- if the apartment is rent ready then do the following:
- pull a list from census_details of all residents set as "current" for each apartment
-if the # of residents is less than the value of apartment_type.occupancy for this
apartment, then list it as available
-if the # of residents is = to the value of apartment_type.occupancy then
-does any resident have a scheduled move out date
-if not, do not list the apartment
-if yes, then list apartment
預先感謝任何幫助或建議。
我試過使用範圍和類方法。我明白如何創建兩者,但僅限於更簡單的查詢。在這裏,我首先獲取公寓清單,然後我需要逐個遍歷該清單,然後查詢census_details,將那裏找到的數字與apartment_type.occupancy中的值進行比較,從中做出更多決策。我不確定在使用示波器,方法或兩者的組合之間使用正確的軌道方式來構建軌道。我不希望任何人爲我寫代碼,更多的幫助如何解決這個問題。 –
讓我知道我是否在正確的軌道上,如果這是正確的方式,或者我弄得一團糟。這裏是我現在在做的: –
把範圍放在CensusDetail範圍內:resident_count, - >(id){where(「status =?and apartment_id =?」,「current」,id)}'創建一個名爲可用的方法正在做上面列出的各種迭代,因爲我正在構建它,如果有必要,我正在創建範圍。我認爲這會起作用。如果是的話,我會發布代碼。如果我不在正確的軌道上,請告訴我。謝謝 –