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
52 # 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
53 def self.find_eager(id)
54 way = Way.find(id, :include => {:way_nodes => :node})
57 # Find a way given it's ID, and in a single SQL call also grab its nodes and tags
59 doc = OSM::API.new.get_xml_doc
60 doc.root << to_xml_node()
64 def to_xml_node(visible_nodes = nil, user_display_name_cache = nil)
65 el1 = XML::Node.new 'way'
66 el1['id'] = self.id.to_s
67 el1['visible'] = self.visible.to_s
68 el1['timestamp'] = self.timestamp.xmlschema
70 user_display_name_cache = {} if user_display_name_cache.nil?
72 if user_display_name_cache and user_display_name_cache.key?(self.user_id)
73 # use the cache if available
74 elsif self.user.data_public?
75 user_display_name_cache[self.user_id] = self.user.display_name
77 user_display_name_cache[self.user_id] = nil
80 el1['user'] = user_display_name_cache[self.user_id] unless user_display_name_cache[self.user_id].nil?
82 # make sure nodes are output in sequence_id order
84 self.way_nodes.each do |nd|
86 # if there is a list of visible nodes then use that to weed out deleted nodes
87 if visible_nodes[nd.node_id]
88 ordered_nodes[nd.sequence_id] = nd.node_id.to_s
91 # otherwise, manually go to the db to check things
92 if nd.node.visible? and nd.node.visible?
93 ordered_nodes[nd.sequence_id] = nd.node_id.to_s
98 ordered_nodes.each do |nd_id|
99 if nd_id and nd_id != '0'
100 e = XML::Node.new 'nd'
106 self.way_tags.each do |tag|
107 e = XML::Node.new 'tag'
118 self.way_nodes.each do |nd|
128 self.way_tags.each do |tag|
144 @nds = Array.new unless @nds
148 def add_tag_keyval(k, v)
149 @tags = Hash.new unless @tags
153 def save_with_history!
161 WayTag.transaction do
164 WayTag.delete_all(['id = ?', self.id])
175 WayNode.transaction do
178 WayNode.delete_all(['id = ?', self.id])
183 nd.id = [self.id, sequence]
190 old_way = OldWay.from_way(self)
191 old_way.timestamp = t
192 old_way.save_with_dependencies!
195 def preconditions_ok?
196 return false if self.nds.empty?
198 node = Node.find(:first, :conditions => ["id = ?", n])
199 unless node and node.visible