Hi all,
I’m hoping that someone out there knows a more efficient way to run a
query on a model with multiple levels of belongs_to’s. I’m working on
a property management application, and the models I have are
Properties, Units, and Leases.
Property —(has_many)–> Units
Units <-- (has_and_belongs_to_many) --> Leases
Leases have two date fields: starts_on, and ends_on, as well as an
integer field called square_feet.
My goal is to figure out the percentage of a property that is leased.
I’m currently doing it with a couple of functions in the property and
unit models. These are:
PROPERTY.RB:
99 # Returns the percentage of a property that is leased
100 def percentage_leased
101 unleased_footage = 0.0
102 leased_footage = 0.0
103 for unit in self.units
104 if unit.leased
105 leased_footage += unit.square_feet
106 else
107 unleased_footage += unit.square_feet
108 end
109 end
110
111 if unleased_footage == 0
112 return 100.0
113 else
114 return (leased_footage / self.total_area) * 100
115 end
116 end # of function percentage_leased
UNIT.RB:
7 # Returns TRUE if the unit is leased, FALSE if it is vacant
8 def leased
9 results = self.leases.find(:all,
10 :conditions => "start_date <=
NOW() AND end_date >= NOW()")
11 if results.size != 1
12 return FALSE
13 else
14 return TRUE
15 end
16 end
In the end, calling property.percentage_leased generates lots of
queries on larger properties. Is there a way to do this with only one
query? Or somehow more efficiently???
Thanks!