1 class Way < ActiveRecord::Base
6 has_many :way_nodes, :foreign_key => 'id', :order => 'sequence_id'
7 has_many :way_tags, :foreign_key => 'id'
9 has_many :old_ways, :foreign_key => 'id', :order => 'version'
11 set_table_name 'current_ways'
13 def self.from_xml(xml, create=false)
21 doc.find('//osm/way').each do |pt|
22 if !create and pt['id'] != '0'
23 way.id = pt['id'].to_i
27 way.timestamp = Time.now
31 way.timestamp = Time.parse(pt['timestamp'])
35 pt.find('tag').each do |tag|
36 way.add_tag_keyval(tag['k'], tag['v'])
39 pt.find('nd').each do |nd|
40 way.add_nd_num(nd['ref'])
50 # Find a way given it's ID, and in a single SQL call also grab its nodes
53 # 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
54 def self.find_eager(id)
55 way = Way.find(id, :include => [:way_tags, {:way_nodes => :node}])
58 # Find a way given it's ID, and in a single SQL call also grab its nodes and tags
60 doc = OSM::API.new.get_xml_doc
61 doc.root << to_xml_node()
65 def to_xml_node(visible_nodes = nil, user_display_name_cache = nil)
66 el1 = XML::Node.new 'way'
67 el1['id'] = self.id.to_s
68 el1['visible'] = self.visible.to_s
69 el1['timestamp'] = self.timestamp.xmlschema
71 user_display_name_cache = {} if user_display_name_cache.nil?
73 if user_display_name_cache and user_display_name_cache.key?(self.user_id)
74 # use the cache if available
75 elsif self.user.data_public?
76 user_display_name_cache[self.user_id] = self.user.display_name
78 user_display_name_cache[self.user_id] = nil
81 el1['user'] = user_display_name_cache[self.user_id] unless user_display_name_cache[self.user_id].nil?
83 # make sure nodes are output in sequence_id order
85 self.way_nodes.each do |nd|
87 # if there is a list of visible nodes then use that to weed out deleted nodes
88 if visible_nodes[nd.node_id]
89 ordered_nodes[nd.sequence_id] = nd.node_id.to_s
92 # otherwise, manually go to the db to check things
93 if nd.node.visible? and nd.node.visible?
94 ordered_nodes[nd.sequence_id] = nd.node_id.to_s
99 ordered_nodes.each do |nd_id|
100 if nd_id and nd_id != '0'
101 e = XML::Node.new 'nd'
107 self.way_tags.each do |tag|
108 e = XML::Node.new 'tag'
119 self.way_nodes.each do |nd|
129 self.way_tags.each do |tag|
145 @nds = Array.new unless @nds
149 def add_tag_keyval(k, v)
150 @tags = Hash.new unless @tags
154 def save_with_history!
162 WayTag.transaction do
165 WayTag.delete_all(['id = ?', self.id])
176 WayNode.transaction do
179 WayNode.delete_all(['id = ?', self.id])
184 nd.id = [self.id, sequence]
191 old_way = OldWay.from_way(self)
192 old_way.timestamp = t
193 old_way.save_with_dependencies!
196 def preconditions_ok?
197 return false if self.nds.empty?
199 node = Node.find(:first, :conditions => ["id = ?", n])
200 unless node and node.visible