]> git.openstreetmap.org Git - rails.git/blob - app/models/note.rb
Merge remote-tracking branch 'upstream/pull/3264'
[rails.git] / app / models / note.rb
1 # == Schema Information
2 #
3 # Table name: notes
4 #
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
12 #  closed_at  :datetime
13 #
14 # Indexes
15 #
16 #  notes_created_at_idx   (created_at)
17 #  notes_tile_status_idx  (tile,status)
18 #  notes_updated_at_idx   (updated_at)
19 #
20
21 class Note < ApplicationRecord
22   include GeoRecord
23
24   has_many :comments, -> { left_joins(:author).where(:visible => true, :users => { :status => [nil, "active", "confirmed"] }).order(:created_at) }, :class_name => "NoteComment", :foreign_key => :note_id
25   has_many :all_comments, -> { left_joins(:author).order(:created_at) }, :class_name => "NoteComment", :foreign_key => :note_id
26
27   validates :id, :uniqueness => true, :presence => { :on => :update },
28                  :numericality => { :on => :update, :only_integer => true }
29   validates :latitude, :longitude, :numericality => { :only_integer => true }
30   validates :closed_at, :presence => true, :if => proc { :status == "closed" }
31   validates :status, :inclusion => %w[open closed hidden]
32
33   validate :validate_position
34
35   scope :visible, -> { where.not(:status => "hidden") }
36   scope :invisible, -> { where(:status => "hidden") }
37
38   after_initialize :set_defaults
39
40   # Sanity check the latitude and longitude and add an error if it's broken
41   def validate_position
42     errors.add(:base, "Note is not in the world") unless in_world?
43   end
44
45   # Close a note
46   def close
47     self.status = "closed"
48     self.closed_at = Time.now.getutc
49     save
50   end
51
52   # Reopen a note
53   def reopen
54     self.status = "open"
55     self.closed_at = nil
56     save
57   end
58
59   # Check if a note is visible
60   def visible?
61     status != "hidden"
62   end
63
64   # Check if a note is closed
65   def closed?
66     !closed_at.nil?
67   end
68
69   # Return the author object, derived from the first comment
70   def author
71     comments.first.author
72   end
73
74   # Return the author IP address, derived from the first comment
75   def author_ip
76     comments.first.author_ip
77   end
78
79   private
80
81   # Fill in default values for new notes
82   def set_defaults
83     self.status = "open" unless attribute_present?(:status)
84   end
85 end