Module: Rating::Extension::ClassMethods

Defined in:
lib/rating/models/rating/extension.rb

Instance Method Summary collapse

Instance Method Details

#rating(options = {}) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/rating/models/rating/extension.rb', line 57

def rating(options = {})
  after_create -> { rating_warm_up scoping: options[:scoping] }, unless: -> { options[:as] == :author }

  has_many :rating_records,
    as:         :resource,
    class_name: '::Rating::Rating',
    dependent:  :destroy

  has_many :rates_records,
    as:         :resource,
    class_name: '::Rating::Rate',
    dependent:  :destroy

  has_many :rated_records,
    as:         :author,
    class_name: '::Rating::Rate',
    dependent:  :destroy

  scope :order_by_rating, lambda { |opts = {}|
    column = opts.fetch(:column, :estimate)
    direction = opts.fetch(:direction, :desc)
    scope = opts[:scope]

    includes(:rating_records)
      .where(Rating.table_name => { scopeable_id: scope&.id, scopeable_type: scope&.class&.base_class&.name })
      .order("#{Rating.table_name}.#{column} #{direction}")
  }

  define_method :rating_options do
    options
  end
end