Guest User

Untitled

a guest
Jan 17th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. data = [
  2. { name: 'Jones',
  3. post: 'President',
  4. city: 'Washington'
  5. },
  6. { name: 'Smith',
  7. post: 'Vice-President',
  8. city: 'Washington'
  9. },
  10. { name: 'Peters',
  11. post: 'Janitor',
  12. city: 'New York'
  13. }
  14. ]
  15.  
  16. data.each do |row|
  17. name = row[:name]; post = row[:post]; city = row[:city]
  18. person = Person.where(name: name).first_or_create
  19. post = Post.where(post: post).first_or_create
  20. location = Location.where(city: city).first_or_create
  21. post.people << person
  22. post.locations << location
  23. location.save; person.save; post.save
  24. end
  25.  
  26. person1 = Person.find_by_name("Jones");
  27. person1.posts.first.locations.first == nil
  28. person2 = Person.find_by_name("Smith");
  29. person2.posts.first.locations.first.city == "Washington"
  30. person3 = Person.find_by_name("Peters");
  31. person3.posts.first.locations.first.city == "New York"
  32.  
  33. class Location < ActiveRecord::Base
  34. belongs_to :post
  35. attr_accessible :city
  36. end
  37.  
  38. class Person < ActiveRecord::Base
  39. attr_accessible :name
  40. has_many :occupations
  41. has_many :posts, through: :occupations
  42. end
  43.  
  44. class Post < ActiveRecord::Base
  45. attr_accessible :post
  46. has_many :occupations
  47. has_many :people, through: :occupations
  48. has_many :locations
  49. end
  50.  
  51. class Occupation < ActiveRecord::Base
  52. belongs_to :person
  53. belongs_to :post
  54. attr_accessible :person_id, :post_id, :since, :till
  55. end
  56.  
  57. class Post
  58. has_and_belongs_to_many :locations
  59. end
  60.  
  61. class Location
  62. has_and_belongs_to_many :posts
  63. end
  64.  
  65. create_table :posts_locations, :id => false do |t|
  66. t.integer :post_id
  67. t.integer :location_id
  68. end
Add Comment
Please, Sign In to add comment