1 class Way < ActiveRecord::Base
4 include ConsistencyValidations
6 set_table_name 'current_ways'
10 has_many :old_ways, :foreign_key => 'id', :order => 'version'
12 has_many :way_nodes, :foreign_key => 'id', :order => 'sequence_id'
13 has_many :nodes, :through => :way_nodes, :order => 'sequence_id'
15 has_many :way_tags, :foreign_key => 'id'
17 has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
18 has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation, :extend => ObjectFinder
20 validates_presence_of :id, :on => :update
21 validates_presence_of :changeset_id,:version, :timestamp
22 validates_uniqueness_of :id
23 validates_inclusion_of :visible, :in => [ true, false ]
24 validates_numericality_of :changeset_id, :version, :integer_only => true
25 validates_numericality_of :id, :on => :update, :integer_only => true
26 validates_associated :changeset
28 def self.from_xml(xml, create=false)
30 p = XML::Parser.string(xml)
33 doc.find('//osm/way').each do |pt|
34 return Way.from_xml_node(pt, create)
36 rescue LibXML::XML::Error, ArgumentError => ex
37 raise OSM::APIBadXMLError.new("way", xml, ex.message)
41 def self.from_xml_node(pt, create=false)
44 if !create and pt['id'] != '0'
45 way.id = pt['id'].to_i
48 way.version = pt['version']
49 raise OSM::APIBadXMLError.new("node", pt, "Changeset is required") if pt['changeset'].nil?
50 way.changeset_id = pt['changeset']
52 # This next section isn't required for the create, update, or delete of ways
54 way.timestamp = Time.now.getutc
58 way.timestamp = Time.parse(pt['timestamp'])
60 # if visible isn't present then it defaults to true
61 way.visible = (pt['visible'] or true)
64 pt.find('tag').each do |tag|
65 way.add_tag_keyval(tag['k'], tag['v'])
68 pt.find('nd').each do |nd|
69 way.add_nd_num(nd['ref'])
75 # Find a way given it's ID, and in a single SQL call also grab its nodes
78 # 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
79 def self.find_eager(id)
80 way = Way.find(id, :include => {:way_nodes => :node})
81 #If waytag had a multipart key that was real, you could do this:
82 #way = Way.find(id, :include => [:way_tags, {:way_nodes => :node}])
85 # Find a way given it's ID, and in a single SQL call also grab its nodes and tags
87 doc = OSM::API.new.get_xml_doc
88 doc.root << to_xml_node()
92 def to_xml_node(visible_nodes = nil, changeset_cache = {}, user_display_name_cache = {})
93 el1 = XML::Node.new 'way'
94 el1['id'] = self.id.to_s
95 el1['visible'] = self.visible.to_s
96 el1['timestamp'] = self.timestamp.xmlschema
97 el1['version'] = self.version.to_s
98 el1['changeset'] = self.changeset_id.to_s
100 if changeset_cache.key?(self.changeset_id)
101 # use the cache if available
103 changeset_cache[self.changeset_id] = self.changeset.user_id
106 user_id = changeset_cache[self.changeset_id]
108 if user_display_name_cache.key?(user_id)
109 # use the cache if available
110 elsif self.changeset.user.data_public?
111 user_display_name_cache[user_id] = self.changeset.user.display_name
113 user_display_name_cache[user_id] = nil
116 if not user_display_name_cache[user_id].nil?
117 el1['user'] = user_display_name_cache[user_id]
118 el1['uid'] = user_id.to_s
121 # make sure nodes are output in sequence_id order
123 self.way_nodes.each do |nd|
125 # if there is a list of visible nodes then use that to weed out deleted nodes
126 if visible_nodes[nd.node_id]
127 ordered_nodes[nd.sequence_id] = nd.node_id.to_s
130 # otherwise, manually go to the db to check things
131 if nd.node and nd.node.visible?
132 ordered_nodes[nd.sequence_id] = nd.node_id.to_s
137 ordered_nodes.each do |nd_id|
138 if nd_id and nd_id != '0'
139 e = XML::Node.new 'nd'
145 self.way_tags.each do |tag|
146 e = XML::Node.new 'tag'
157 self.way_nodes.each do |nd|
167 self.way_tags.each do |tag|
183 @nds = Array.new unless @nds
187 def add_tag_keyval(k, v)
188 @tags = Hash.new unless @tags
190 # duplicate tags are now forbidden, so we can't allow values
191 # in the hash to be overwritten.
192 raise OSM::APIDuplicateTagsError.new("way", self.id, k) if @tags.include? k
198 # the integer coords (i.e: unscaled) bounding box of the way, assuming
199 # straight line segments.
201 lons = nodes.collect { |n| n.longitude }
202 lats = nodes.collect { |n| n.latitude }
203 [ lons.min, lats.min, lons.max, lats.max ]
206 def update_from(new_way, user)
207 check_consistency(self, new_way, user)
208 unless new_way.preconditions_ok?
209 raise OSM::APIPreconditionFailedError.new("Cannot update way #{self.id}: data is invalid.")
212 self.changeset_id = new_way.changeset_id
213 self.changeset = new_way.changeset
214 self.tags = new_way.tags
215 self.nds = new_way.nds
220 def create_with_history(user)
221 check_create_consistency(self, user)
222 unless self.preconditions_ok?
223 raise OSM::APIPreconditionFailedError.new("Cannot create way: data is invalid.")
230 def preconditions_ok?
231 return false if self.nds.empty?
232 if self.nds.length > APP_CONFIG['max_number_of_way_nodes']
233 raise OSM::APITooManyWayNodesError.new(self.nds.length, APP_CONFIG['max_number_of_way_nodes'])
236 node = Node.find(:first, :conditions => ["id = ?", n])
237 unless node and node.visible
238 raise OSM::APIPreconditionFailedError.new("The node with id #{n} either does not exist, or is not visible")
244 def delete_with_history!(new_way, user)
246 raise OSM::APIAlreadyDeletedError.new("way", new_way.id)
249 # need to start the transaction here, so that the database can
250 # provide repeatable reads for the used-by checks. this means it
251 # shouldn't be possible to get race conditions.
253 check_consistency(self, new_way, user)
254 if RelationMember.find(:first, :joins => "INNER JOIN current_relations ON current_relations.id=current_relation_members.id",
255 :conditions => [ "visible = ? AND member_type='Way' and member_id=? ", true, self.id])
256 raise OSM::APIPreconditionFailedError.new("You need to make sure that this way is not a member of a relation.")
258 self.changeset_id = new_way.changeset_id
259 self.changeset = new_way.changeset
269 # Find nodes that belong to this way only
270 def unshared_node_ids
271 node_ids = self.nodes.collect { |node| node.id }
273 unless node_ids.empty?
274 way_nodes = WayNode.find(:all, :conditions => "node_id in (#{node_ids.join(',')}) and id != #{self.id}")
275 node_ids = node_ids - way_nodes.collect { |way_node| way_node.node_id }
281 # Temporary method to match interface to nodes
287 # if any referenced nodes are placeholder IDs (i.e: are negative) then
288 # this calling this method will fix them using the map from placeholders
290 def fix_placeholders!(id_map, placeholder_id = nil)
291 self.nds.map! do |node_id|
293 new_id = id_map[:node][node_id]
294 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?
304 def save_with_history!
307 # update the bounding box, note that this has to be done both before
308 # and after the save, so that nodes from both versions are included in the
309 # bbox. we use a copy of the changeset so that it isn't reloaded
312 cs.update_bbox!(bbox) unless nodes.empty?
320 WayTag.delete_all(['id = ?', self.id])
330 WayNode.delete_all(['id = ?', self.id])
334 nd.id = [self.id, sequence]
340 old_way = OldWay.from_way(self)
341 old_way.timestamp = t
342 old_way.save_with_dependencies!
344 # reload the way so that the nodes array points to the correct
348 # update and commit the bounding box, now that way nodes
349 # have been updated and we're in a transaction.
350 cs.update_bbox!(bbox) unless nodes.empty?
352 # tell the changeset we updated one element only