Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data = [
- { name: 'Jones',
- post: 'President',
- city: 'Washington'
- },
- { name: 'Smith',
- post: 'Vice-President',
- city: 'Washington'
- },
- { name: 'Peters',
- post: 'Janitor',
- city: 'New York'
- }
- ]
- data.each do |row|
- name = row[:name]; post = row[:post]; city = row[:city]
- person = Person.where(name: name).first_or_create
- post = Post.where(post: post).first_or_create
- location = Location.where(city: city).first_or_create
- post.people << person
- post.locations << location
- location.save; person.save; post.save
- end
- person1 = Person.find_by_name("Jones");
- person1.posts.first.locations.first == nil
- person2 = Person.find_by_name("Smith");
- person2.posts.first.locations.first.city == "Washington"
- person3 = Person.find_by_name("Peters");
- person3.posts.first.locations.first.city == "New York"
- class Location < ActiveRecord::Base
- belongs_to :post
- attr_accessible :city
- end
- class Person < ActiveRecord::Base
- attr_accessible :name
- has_many :occupations
- has_many :posts, through: :occupations
- end
- class Post < ActiveRecord::Base
- attr_accessible :post
- has_many :occupations
- has_many :people, through: :occupations
- has_many :locations
- end
- class Occupation < ActiveRecord::Base
- belongs_to :person
- belongs_to :post
- attr_accessible :person_id, :post_id, :since, :till
- end
- class Post
- has_and_belongs_to_many :locations
- end
- class Location
- has_and_belongs_to_many :posts
- end
- create_table :posts_locations, :id => false do |t|
- t.integer :post_id
- t.integer :location_id
- end
Add Comment
Please, Sign In to add comment