]> git.openstreetmap.org Git - rails.git/blob - app/models/note.rb
Merge remote-tracking branch 'upstream/pull/2010'
[rails.git] / app / models / note.rb
1 # == Schema Information
2 #
3 # Table name: notes
4 #
5 #  id         :integer          not null, primary key
6 #  latitude   :integer          not null
7 #  longitude  :integer          not null
8 #  tile       :integer          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 < ActiveRecord::Base
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
26   validates :id, :uniqueness => true, :presence => { :on => :update },
27                  :numericality => { :on => :update, :integer_only => true }
28   validates :latitude, :longitude, :numericality => { :only_integer => true }
29   validates :closed_at, :presence => true, :if => proc { :status == "closed" }
30   validates :status, :inclusion => %w[open closed hidden]
31
32   validate :validate_position
33
34   scope :visible, -> { where.not(:status => "hidden") }
35   scope :invisible, -> { where(:status => "hidden") }
36
37   after_initialize :set_defaults
38
39   # Sanity check the latitude and longitude and add an error if it's broken
40   def validate_position
41     errors.add(:base, "Note is not in the world") unless in_world?
42   end
43
44   # Close a note
45   def close
46     self.status = "closed"
47     self.closed_at = Time.now.getutc
48     save
49   end
50
51   # Reopen a note
52   def reopen
53     self.status = "open"
54     self.closed_at = nil
55     save
56   end
57
58   # Check if a note is visible
59   def visible?
60     status != "hidden"
61   end
62
63   # Check if a note is closed
64   def closed?
65     !closed_at.nil?
66   end
67
68   # Return the author object, derived from the first comment
69   def author
70     comments.first.author
71   end
72
73   # Return the author IP address, derived from the first comment
74   def author_ip
75     comments.first.author_ip
76   end
77
78   private
79
80   # Fill in default values for new notes
81   def set_defaults
82     self.status = "open" unless attribute_present?(:status)
83   end
84 end