Postgres,Rails和GROUP

时间:2011-08-18 21:18:12

标签: ruby-on-rails-3 postgresql activerecord

我正在使用Rails 3应用程序。我有3个模型:用户,场地和评级。

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

我需要按邻居分组所有场地,附近的名称,邻里组中所有场馆的平均评分,邻里组中所有场馆的评分总数,所有场馆的平均纬度在邻里小组中,以及邻里小组中所有场地的平均经度。

我不太确定如何使用ActiveRecord和Postgres到达那里,有什么建议吗?

2 个答案:

答案 0 :(得分:0)

以下是我的建议:

考虑http://geokit.rubyforge.org/它将允许您执行“ActiveRecord基于距离的查找程序。例如,您可以在50英里范围内找到数据库中的所有点。”我想,那是你的邻居。

其次,我会使用Postgresql视图进行性能和数据聚合。以下是文档的链接:http://developer.postgresql.org/pgdocs/postgres/sql-createview.html

答案 1 :(得分: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