-1

我很难理解如何构建这个查询。我不确定是否应该尝试创建一堆范围并尝试链接它们。还是我将其放入类方法中?还是我会两者兼而有之?如果有人能给我一个简短的例子,它会让我不会跳出窗外,我已经为此工作了一个多星期。

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  

提前感谢您的任何帮助或建议。

4

1 回答 1

0

我还没有清理它,但这对我有用,所以我想分享。

公寓类型.rb

class ApartmentType < ActiveRecord::Base
  has_many  :apartments, :dependent => :nullify
end

census_detail.rb

class CensusDetail < ActiveRecord::Base
  belongs_to  :resident_contacts
  belongs_to  :apartments
  scope :get_current_residents,  ->(id) { where("status = ? and apartment_id = ?", "current", id) }
end

大部分工作都在其中进行的公寓.rb

class Apartment < ActiveRecord::Base  
  belongs_to :apartment_type  
  has_many  :census_details  
  has_many  :residents, :through => :census_details  
  scope :rent_ready,      ->  { where(:enabled => true) }

  def self.available
    available_apartments = []
    rent_ready_apartments = self.rent_ready.all

    rent_ready_apartments.each do |apt|
      tmp = ApartmentType.where('id = ?', apt.apartment_type_id).pluck(:occupancy)
      occupancy = tmp[0]
      current_residents = CensusDetail.get_current_residents(apt.id)
      resident_count = current_residents.count

      if resident_count < occupancy
        available_apartments << apt
      end

      if resident_count = occupancy
        scheduled = false
        current_residents.each do |res|
          if res.moveout_date
            scheduled = true
          end
        end
        if scheduled == true
          available_apartments << apt
        end
      end
    end
    available_apartments
  end
end

代码有点难看,但到目前为止它通过了我的测试。我会编辑我原来的问题而不是回答,以防有人有更好的方法来做这件事,但每次我做我的问题都会被否决。如果有人知道更好的方法,请告诉我,因为我在应用程序中的某个点上大约有 50 个表,现在所有这些都与复杂的查询联系在一起。

于 2013-04-13T17:28:23.667 回答