Ruby on Rails: Order users based on average ratings with most reviews?

前端 未结 1 1832
难免孤独
难免孤独 2020-12-21 11:32

I\'m able to display the items and their reviews that are within the shop. How do I get the top items with most reviews? My reviews are in another database table than shop a

相关标签:
1条回答
  • 2020-12-21 11:57

    If I understood correctly Your ER model, You can try this:

    @items = Item.where(:shop_name => @shop.name).joins(:reviews)
      .select("items.id, avg(reviews.rating) as average_rating, count(reviews.id) as number_of_reviews")
      .group("items.id")
      .order("average_rating DESC, number_of_reviews DESC")
    

    There could some typos, but You get the idea. Also probably You will want to create some kind of weighted score, otherwise in this case item with one 5 star review will be higher than item with fifty 4 star reviews.

    Also all the custom columns I defined in select block will be of string type, so You will need to typecast those manually if You will do any arithmetic operations on them.

    0 讨论(0)
提交回复
热议问题