Skip to content
Snippets Groups Projects
view.rb 887 B
Newer Older
# == Schema Information
#
# Table name: views
#
#  id            :integer          not null, primary key
#  viewable_id   :integer
#  viewable_type :string
#  user_id       :integer
#  created_at    :datetime         not null
#  updated_at    :datetime         not null
#

Mateus Rambo Strey's avatar
Mateus Rambo Strey committed
class View < ApplicationRecord
  # *current_user* views *viewable*
  include Trackable

  belongs_to :viewable, polymorphic: true, counter_cache: true
  validates_presence_of :user, :viewable

  before_create :current_time_greater_than_last

Lucas Ernesto Kindinger's avatar
Lucas Ernesto Kindinger committed
  scope :created_last, ->(user) { where(user: user).order('created_at DESC').limit(1) }
  def recipient
    viewable
  end

  private

  def current_time_greater_than_last
Lucas Ernesto Kindinger's avatar
Lucas Ernesto Kindinger committed
    last_view = viewable.views.created_last(user).first

    unless last_view.blank?
      return false if Time.now < (last_view.created_at + 1.days)
    end

    true
  end