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 # index_notes_on_description (to_tsvector('english'::regconfig, description)) USING gin
20 # notes_created_at_idx (created_at)
21 # notes_tile_status_idx (tile,status)
22 # notes_updated_at_idx (updated_at)
26 # notes_user_id_fkey (user_id => users.id)
29 class Note < ApplicationRecord
32 belongs_to :author, :class_name => "User", :foreign_key => "user_id", :optional => true
34 has_many :comments, -> { left_joins(:author).where(:visible => true, :users => { :status => [nil, "active", "confirmed"] }).order(:created_at) }, :class_name => "NoteComment", :foreign_key => :note_id
35 has_many :all_comments, -> { left_joins(:author).order(:created_at) }, :class_name => "NoteComment", :foreign_key => :note_id, :inverse_of => :note
36 has_many :subscriptions, :class_name => "NoteSubscription"
37 has_many :subscribers, :through => :subscriptions, :source => :user
39 validates :id, :uniqueness => true, :presence => { :on => :update },
40 :numericality => { :on => :update, :only_integer => true }
41 validates :latitude, :longitude, :numericality => { :only_integer => true }
42 validates :closed_at, :presence => true, :if => proc { :status == "closed" }
43 validates :status, :inclusion => %w[open closed hidden]
45 validate :validate_position
47 scope :visible, -> { where.not(:status => "hidden") }
48 scope :invisible, -> { where(:status => "hidden") }
50 after_initialize :set_defaults
52 DEFAULT_FRESHLY_CLOSED_LIMIT = 7.days
54 # Sanity check the latitude and longitude and add an error if it's broken
56 errors.add(:base, "Note is not in the world") unless in_world?
61 self.status = "closed"
62 self.closed_at = Time.now.utc
73 # Check if a note is visible
78 # Check if a note is closed
84 return false unless closed?
86 Time.now.utc < freshly_closed_until
89 def freshly_closed_until
90 return nil unless closed?
92 closed_at + DEFAULT_FRESHLY_CLOSED_LIMIT
95 # Return the note's description, derived from the first comment
97 if user_ip.nil? && user_id.nil?
98 all_comments.first.body
100 RichText.new("text", super)
104 # Return the note's author object, derived from the first comment
106 if user_ip.nil? && user_id.nil?
107 all_comments.first.author
115 # Fill in default values for new notes
117 self.status = "open" unless attribute_present?(:status)