code_junkie

How can I upsert a bunch of ActiveRecord objects and relationships in Rails?

Nov 10th, 2011
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. # routes is an array of [number, destination] that I build while iterating over the data
  2. routes.uniq.each do |route|
  3. number = route[0]
  4. destination = route[1]
  5.  
  6. r = Route.find_by_number_and_destination(number, destination)
  7.  
  8. if !r
  9. r = Route.new :number => number, :destination => destination
  10. r.save
  11. end
  12.  
  13. # I have to check if it already exists because I can't find a way
  14. # to create a uniqueness constraint on the join table with 2 foreign keys
  15. r.stops << stop unless r.stops.include? stop
  16. end
  17.  
  18. class Route < ActiveRecord::Base
  19. has_and_belongs_to_many :stops
  20. belongs_to :stop, :foreign_key => 'destination_id'
  21. end
  22.  
  23. class Stop < ActiveRecorde::Base
  24. has_and_belongs_to_many :routes
  25. end
  26.  
  27. create_table :routes do |t|
  28. t.integer :destination_id
  29. # Any other information you want to store about routes
  30. end
  31.  
  32. create_table :stops do |t|
  33. # Any other information you want to store about stops
  34. end
  35.  
  36. create_table :routes_stops, :primary_key => [:route_id, :stop_id] do |t|
  37. t.integer :route_id
  38. t.integer :stop_id
  39. end
  40.  
  41. # First, find all the relevant routes, just for caching.
  42. Route.find(numbers)
  43.  
  44. r = Route.find(number)
  45. r.destination_id = destination
  46. r.stops << stop
Add Comment
Please, Sign In to add comment