0

I've been trying to get a list of restaurants to be ordered and displayed in my rails app by average ratings and total number of reviews in descending order. So far I am able to collect and order them from the database (psql) correctly but the problem is that the restaurants that don't have any reviews or ratings don't show up in the list (meaning they are not displayed on the front end). These are my models:

class Restaurant < ActiveRecord::Base
  belongs_to :user
  has_many :reviews, dependent: :destroy
  validates :name, length: {minimum: 3}, uniqueness: true
end

class Review < ActiveRecord::Base
 belongs_to :restaurant
 belongs_to :user
 validates :rating, presence: true, inclusion: (1..5)
end

Here is the code in the restaurants controller that request data from database:

def index
  if params[:search]
    @restaurants = Restaurant.search(params[:search]).order("created_at DESC")
  else
    @restaurants =Restaurant.joins(:reviews).group("restaurants.id").order("AVG(reviews.rating) DESC")
 end
end

I'm clearly missing something here but I don't know what! Searched everywhere for an answer but can't find it.. Ideally I would like the restaurants with no ratings or reviews to show up at the bottom of the list in order of created first

1 Answer 1

2

The Rails join by default does an inner join. So it's excluding restaurants that have no reviews.

def index
  if params[:search]
    @restaurants = Restaurant
      .search(params[:search])
      .order(:created_at => :desc)
  else
    @restaurants = Restaurant
      .joins('LEFT JOIN reviews ON restaurants.id = reviews.restaurant_id')
      .group('restaurants.id')
      .order('AVG(reviews.rating) DESC NULLS LAST')
  end
end
2
  • I tried this and had to change (:restaurants => :id) to ('restaurants.id') and it worked but the only issue is the reviewed and rated restaurants appear in order but at the bottom of the list with the non reviewed and rated restaurants appearing at the top. Is there a way of making them appear at the bottom in order of what was created first? I tried adding restaurants.created_at DESC at the end but it ruins the order of reviewed restaurants. Thanks for the help.
    – enkido
    Apr 1, 2015 at 9:54
  • I updated my answer for the ordering. Try the NULLS LAST part if you're using PostgreSQL. Apr 1, 2015 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.