2011-08-18 61 views
0

我有一個Rails 3應用程序正在工作。我有3個模型:用戶,場地和評分。Postgres,Rails和GROUP

User.rb:

# attributes: 
# name, email => String 
class User < ActiveRecord::Base 
    has_many :ratings 
    has_many :venues, :through => :ratings, :uniq => true 
    ... 
end 

Venue.rb:

# attributes: 
# name, address, city, state, zip, neighborhood => String 
# latitude, longitude => Float 
class Venue < ActiveRecord::Base 
    has_many :ratings 
    has_many :users 
    ... 

    def average_rating 
     sum = 0 
     self.ratings.each do |rating| 
     sum += rating.value 
     end 
     sum.to_f/self.number_of_ratings.to_f 
    end 

    def number_of_ratings 
     self.ratings.count 
    end 
end 

Rating.rb:

# attributes: 
# venue_id, user_id => Integer 
# value => String 
class Rating < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :venue 
    ... 
end 

我需要通過居委會分組的所有場館,名稱鄰里組中所有場館的平均評分,n中所有場館的評分總數eighborhood組,鄰域組中所有場館的平均緯度以及鄰域組中所有場館的平均經度。

我不太清楚如何使用ActiveRecord和Postgres來完成任何建議?

回答

0

這是我已經做了,使其工作;不過,我覺得他們可能是一個更有效的方式來運行postres查詢和鄰居組,但我沒有任何運氣來解決它。

neighborhoods = @venues.select('DISTINCT(venues.neighborhood)').map(&:neighborhood) 
neighborhoods.each do |neighborhood| 
    venues_in_neighborhood = @venues.where(:neighborhood => neighborhood).includes(:ratings) 
    avg_rating = venues_in_neighborhood.average('ratings.value').to_f   
    number_of_ratings = Rating.includes(:venue).where('venues.neighborhood' => neighborhood).count 
    avg_latitude = venues_in_neighborhood.average('latitude').to_f 
    avg_longitude = venues_in_neighborhood.average('longitude').to_f 

    @response << {:name => neighborhood, 
        :latitude => avg_latitude, 
        :longitude => avg_longitude, 
        :rating => avg_rating, 
        :numberOfRatings => number_of_ratings} 
end