Skip to content
Snippets Groups Projects
review.rb 1.61 KiB
Newer Older
# == Schema Information
#
# Table name: reviews
#
#  id              :integer          not null, primary key
#  name            :string
#  description     :text
#  pros            :text
#  cons            :text
#  reviewable_id   :integer
#  reviewable_type :string
#  user_id         :integer
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#  rates_count     :integer          default("0")
#

class Review < ActiveRecord::Base
  # *current_user* review *reviewable*
  include Trackable

  belongs_to :reviewable, polymorphic: true
  has_many :review_ratings
  has_many :ratings, through: :review_ratings
  has_many :rates
Mateus Rambo Strey's avatar
Mateus Rambo Strey committed
  has_many :complaints, as: :complaintable

  validates_presence_of :user, :reviewable, :review_ratings
Mateus Rambo Strey's avatar
Mateus Rambo Strey committed
  validates_inclusion_of :reviewable_type, in: %w(LearningObject Collection), message: 'Only LearningObjects and Collections are reviewable.'
  validates_uniqueness_of :user, scope: [:reviewable_id, :reviewable_type]
  accepts_nested_attributes_for :review_ratings

  default_scope { includes(:user) }
  def rating_values
    review_ratings.includes(:rating).map { |r| {rating: r.rating, value: r.value} }
  def rating_average
    review_ratings.average(:value).floor(1).to_f
  end

  def rates_percentage
    return false if rates.count < 5
    approved = rates.where(approves: true).count
    (approved.to_f / rates.count.to_f) * 100
  end

  def rated? (user)
    !Rate.where(user: user, review: self).first.nil?
  def user_approves? (user)
    return Rate.where(user: user, review: self).first.approves if rated? user
    nil