I have a Rails 3 application I’m working on. I have 3 models: User, Venue, and Rating.
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
I need to get all venues grouped by neighborhood, with the name of the neighborhood, the average rating for all venues in the neighborhood group, the total number of ratings for all venues in the neighborhood group, the average latitude of all venues in the neighborhood group, and the average longitude of all venues in the neighborhood group.
I’m not quite sure how to get there using ActiveRecord and Postgres, any suggestions?
This is what I’ve done to make it work; however, I feel like their might be a more efficient way to run a postres query and group by neighborhood, but I haven’t had any luck in figuring it out.