1 class Way < ActiveRecord::Base
4 include ConsistencyValidations
8 self.table_name = "current_ways"
12 has_many :old_ways, -> { order(:version) }
14 has_many :way_nodes, -> { order(:sequence_id) }
15 has_many :nodes, -> { order("sequence_id") }, :through => :way_nodes
19 has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
20 has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
22 validates_presence_of :id, :on => :update
23 validates_presence_of :changeset_id,:version, :timestamp
24 validates_uniqueness_of :id
25 validates_inclusion_of :visible, :in => [ true, false ]
26 validates_numericality_of :changeset_id, :version, :integer_only => true
27 validates_numericality_of :id, :on => :update, :integer_only => true
28 validates_associated :changeset
30 scope :visible, -> { where(:visible => true) }
31 scope :invisible, -> { where(:visible => false) }
33 # Read in xml as text and return it's Way object representation
34 def self.from_xml(xml, create=false)
36 p = XML::Parser.string(xml)
39 doc.find('//osm/way').each do |pt|
40 return Way.from_xml_node(pt, create)
42 raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/way element.")
43 rescue LibXML::XML::Error, ArgumentError => ex
44 raise OSM::APIBadXMLError.new("way", xml, ex.message)
48 def self.from_xml_node(pt, create=false)
51 raise OSM::APIBadXMLError.new("way", pt, "Version is required when updating") unless create or not pt['version'].nil?
52 way.version = pt['version']
53 raise OSM::APIBadXMLError.new("way", pt, "Changeset id is missing") if pt['changeset'].nil?
54 way.changeset_id = pt['changeset']
57 raise OSM::APIBadXMLError.new("way", pt, "ID is required when updating") if pt['id'].nil?
58 way.id = pt['id'].to_i
59 # .to_i will return 0 if there is no number that can be parsed.
60 # We want to make sure that there is no id with zero anyway
61 raise OSM::APIBadUserInput.new("ID of way cannot be zero when updating.") if way.id == 0
64 # We don't care about the timestamp nor the visibility as these are either
65 # set explicitly or implicit in the action. The visibility is set to true,
66 # and manually set to false before the actual delete.
72 # Add in any tags from the XML
73 pt.find('tag').each do |tag|
74 raise OSM::APIBadXMLError.new("way", pt, "tag is missing key") if tag['k'].nil?
75 raise OSM::APIBadXMLError.new("way", pt, "tag is missing value") if tag['v'].nil?
76 way.add_tag_keyval(tag['k'], tag['v'])
79 pt.find('nd').each do |nd|
80 way.add_nd_num(nd['ref'])
86 # Find a way given it's ID, and in a single SQL call also grab its nodes
89 # You can't pull in all the tags too unless we put a sequence_id on the way_tags table and have a multipart key
90 def self.find_eager(id)
91 way = Way.find(id, :include => {:way_nodes => :node})
92 #If waytag had a multipart key that was real, you could do this:
93 #way = Way.find(id, :include => [:way_tags, {:way_nodes => :node}])
96 # Find a way given it's ID, and in a single SQL call also grab its nodes and tags
98 doc = OSM::API.new.get_xml_doc
99 doc.root << to_xml_node()
103 def to_xml_node(visible_nodes = nil, changeset_cache = {}, user_display_name_cache = {})
104 el1 = XML::Node.new 'way'
105 el1['id'] = self.id.to_s
106 add_metadata_to_xml_node(el1, self, changeset_cache, user_display_name_cache)
108 # make sure nodes are output in sequence_id order
110 self.way_nodes.each do |nd|
112 # if there is a list of visible nodes then use that to weed out deleted nodes
113 if visible_nodes[nd.node_id]
114 ordered_nodes[nd.sequence_id] = nd.node_id.to_s
117 # otherwise, manually go to the db to check things
118 if nd.node and nd.node.visible?
119 ordered_nodes[nd.sequence_id] = nd.node_id.to_s
124 ordered_nodes.each do |nd_id|
125 if nd_id and nd_id != '0'
126 e = XML::Node.new 'nd'
132 self.way_tags.each do |tag|
133 e = XML::Node.new 'tag'
144 self.way_nodes.each do |nd|
154 self.way_tags.each do |tag|
170 @nds = Array.new unless @nds
174 def add_tag_keyval(k, v)
175 @tags = Hash.new unless @tags
177 # duplicate tags are now forbidden, so we can't allow values
178 # in the hash to be overwritten.
179 raise OSM::APIDuplicateTagsError.new("way", self.id, k) if @tags.include? k
185 # the integer coords (i.e: unscaled) bounding box of the way, assuming
186 # straight line segments.
188 lons = nodes.collect { |n| n.longitude }
189 lats = nodes.collect { |n| n.latitude }
190 BoundingBox.new(lons.min, lats.min, lons.max, lats.max)
193 def update_from(new_way, user)
196 check_consistency(self, new_way, user)
197 unless new_way.preconditions_ok?(self.nds)
198 raise OSM::APIPreconditionFailedError.new("Cannot update way #{self.id}: data is invalid.")
201 self.changeset_id = new_way.changeset_id
202 self.changeset = new_way.changeset
203 self.tags = new_way.tags
204 self.nds = new_way.nds
210 def create_with_history(user)
211 check_create_consistency(self, user)
212 unless self.preconditions_ok?
213 raise OSM::APIPreconditionFailedError.new("Cannot create way: data is invalid.")
220 def preconditions_ok?(old_nodes = [])
221 return false if self.nds.empty?
222 if self.nds.length > MAX_NUMBER_OF_WAY_NODES
223 raise OSM::APITooManyWayNodesError.new(self.id, self.nds.length, MAX_NUMBER_OF_WAY_NODES)
226 # check only the new nodes, for efficiency - old nodes having been checked last time and can't
227 # be deleted when they're in-use.
228 new_nds = (self.nds - old_nodes).sort.uniq
230 unless new_nds.empty?
231 db_nds = Node.where(:id => new_nds, :visible => true)
233 if db_nds.length < new_nds.length
234 missing = new_nds - db_nds.collect { |n| n.id }
235 raise OSM::APIPreconditionFailedError.new("Way #{self.id} requires the nodes with id in (#{missing.join(',')}), which either do not exist, or are not visible.")
242 def delete_with_history!(new_way, user)
244 raise OSM::APIAlreadyDeletedError.new("way", new_way.id)
247 # need to start the transaction here, so that the database can
248 # provide repeatable reads for the used-by checks. this means it
249 # shouldn't be possible to get race conditions.
252 check_consistency(self, new_way, user)
253 rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Way", :member_id => id }).order(:id)
254 raise OSM::APIPreconditionFailedError.new("Way #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty?
256 self.changeset_id = new_way.changeset_id
257 self.changeset = new_way.changeset
266 # Temporary method to match interface to nodes
272 # if any referenced nodes are placeholder IDs (i.e: are negative) then
273 # this calling this method will fix them using the map from placeholders
275 def fix_placeholders!(id_map, placeholder_id = nil)
276 self.nds.map! do |node_id|
278 new_id = id_map[:node][node_id]
279 raise OSM::APIBadUserInput.new("Placeholder node not found for reference #{node_id} in way #{self.id.nil? ? placeholder_id : self.id}") if new_id.nil?
289 def save_with_history!
292 # update the bounding box, note that this has to be done both before
293 # and after the save, so that nodes from both versions are included in the
294 # bbox. we use a copy of the changeset so that it isn't reloaded
297 cs.update_bbox!(bbox) unless nodes.empty?
305 WayTag.delete_all(:way_id => self.id)
315 WayNode.delete_all(:way_id => self.id)
319 nd.id = [self.id, sequence]
325 old_way = OldWay.from_way(self)
326 old_way.timestamp = t
327 old_way.save_with_dependencies!
329 # reload the way so that the nodes array points to the correct
333 # update and commit the bounding box, now that way nodes
334 # have been updated and we're in a transaction.
335 cs.update_bbox!(bbox) unless nodes.empty?
337 # tell the changeset we updated one element only