sql - Ordering data from table by average rating and number of reviews including objects with no rating or reviews yet using active record -


i've been trying list of restaurants ordered , displayed in rails app average ratings , total number of reviews in descending order. far able collect , order them database (psql) correctly problem restaurants don't have reviews or ratings don't show in list (meaning not displayed on front end). these 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 code in restaurants controller request data 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 missing here don't know what! searched everywhere answer can't find it.. ideally restaurants no ratings or reviews show @ bottom of list in order of created first

the rails join default inner join. it's excluding restaurants 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 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -