Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # routes is an array of [number, destination] that I build while iterating over the data
- routes.uniq.each do |route|
- number = route[0]
- destination = route[1]
- r = Route.find_by_number_and_destination(number, destination)
- if !r
- r = Route.new :number => number, :destination => destination
- r.save
- end
- # I have to check if it already exists because I can't find a way
- # to create a uniqueness constraint on the join table with 2 foreign keys
- r.stops << stop unless r.stops.include? stop
- end
- class Route < ActiveRecord::Base
- has_and_belongs_to_many :stops
- belongs_to :stop, :foreign_key => 'destination_id'
- end
- class Stop < ActiveRecorde::Base
- has_and_belongs_to_many :routes
- end
- create_table :routes do |t|
- t.integer :destination_id
- # Any other information you want to store about routes
- end
- create_table :stops do |t|
- # Any other information you want to store about stops
- end
- create_table :routes_stops, :primary_key => [:route_id, :stop_id] do |t|
- t.integer :route_id
- t.integer :stop_id
- end
- # First, find all the relevant routes, just for caching.
- Route.find(numbers)
- r = Route.find(number)
- r.destination_id = destination
- r.stops << stop
Add Comment
Please, Sign In to add comment