lundi 27 avril 2015

Ruby on Rails: Issue sorting index based on average review rating

So I am trying to order my Provider's (similar to a User) index by average rating, with the highest at the top. It works, but adds an extra row for each Review that a Provider has. E.g. If I have one Provider with 3 Reviews, the Provider will show up 3 times in the Providers index. Rating is a column on Reviews and is an integer between 1-5.

provider.rb

class Provider < ActiveRecord::Base
  belongs_to :user, foreign_key: 'user_id', autosave: true
  has_many :reviews, dependent: :destroy
end

review.rb

class Review < ActiveRecord::Base
  belongs_to :user, foreign_key: 'user_id'
  belongs_to :provider, foreign_key: 'provider_id'
end

providers_controller.rb

class ProvidersController < ApplicationController
  before_action :set_provider, only: [:show, :edit, :update, :destroy]

 def index
   @providers = Provider.all
                 .joins(:reviews)
                 .order("reviews.rating DESC")
   @reviews = Review.find_by(params[:provider_id])
 end

index.html.erb

 <% @providers.each do |provider| %>
  <tr>
    <td><%= link_to provider.name, provider_path(provider.id) %></td>
    <td><%= provider.industry %></td>
    <td><%= provider.experience %></td>
    <td><%= provider.description %></td>
    <td><%= provider.reviews.average(:rating) %></td>
  </tr>
<% end %>

Its probably something really silly as I am quite new to Ruby + Rails, but I cant seem to figure it out/find an relevant info. I've tried adding "AVG(reviews.rating) DESC" to the order method but that gives me an SQLite exception error.

Any help would be muchly appreciated!!! Happy to provide any more info if needed.

Aucun commentaire:

Enregistrer un commentaire