1 # == Schema Information
5 # id :bigint(8) not null, primary key
6 # latitude :integer not null
7 # longitude :integer not null
8 # tile :bigint(8) not null
9 # updated_at :datetime not null
10 # created_at :datetime not null
11 # status :enum not null
13 # description :text default(""), not null
19 # notes_created_at_idx (created_at)
20 # notes_tile_status_idx (tile,status)
21 # notes_updated_at_idx (updated_at)
25 # notes_user_id_fkey (user_id => users.id)
28 class Note < ApplicationRecord
31 belongs_to :author, :class_name => "User", :foreign_key => "user_id", :optional => true
33 has_many :comments, -> { left_joins(:author).where(:visible => true, :users => { :status => [nil, "active", "confirmed"] }).order(:created_at) }, :class_name => "NoteComment", :foreign_key => :note_id
34 has_many :all_comments, -> { left_joins(:author).order(:created_at) }, :class_name => "NoteComment", :foreign_key => :note_id, :inverse_of => :note
35 has_many :subscriptions, :class_name => "NoteSubscription"
36 has_many :subscribers, :through => :subscriptions, :source => :user
38 validates :id, :uniqueness => true, :presence => { :on => :update },
39 :numericality => { :on => :update, :only_integer => true }
40 validates :latitude, :longitude, :numericality => { :only_integer => true }
41 validates :closed_at, :presence => true, :if => proc { :status == "closed" }
42 validates :status, :inclusion => %w[open closed hidden]
44 validate :validate_position
46 scope :visible, -> { where.not(:status => "hidden") }
47 scope :invisible, -> { where(:status => "hidden") }
49 after_initialize :set_defaults
51 DEFAULT_FRESHLY_CLOSED_LIMIT = 7.days
53 # Sanity check the latitude and longitude and add an error if it's broken
55 errors.add(:base, "Note is not in the world") unless in_world?
60 self.status = "closed"
61 self.closed_at = Time.now.utc
72 # Check if a note is visible
77 # Check if a note is closed
83 return false unless closed?
85 Time.now.utc < freshly_closed_until
88 def freshly_closed_until
89 return nil unless closed?
91 closed_at + DEFAULT_FRESHLY_CLOSED_LIMIT
94 # Return the note's description, derived from the first comment
96 if user_ip.nil? && user_id.nil?
97 all_comments.first.body
99 RichText.new("text", super)
103 # Return the note's author object, derived from the first comment
105 if user_ip.nil? && user_id.nil?
106 all_comments.first.author
114 # Fill in default values for new notes
116 self.status = "open" unless attribute_present?(:status)