Guest User

Untitled

a guest
Mar 3rd, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. require 'rubygems'
  2. require 'dm-core'
  3.  
  4. DataMapper.setup(:default,
  5. :adapter => 'mysql',
  6. :host => 'localhost',
  7. :username => 'root',
  8. :password => '',
  9. :database => 'dm_core_test',
  10. :encoding => 'utf8'
  11. )
  12.  
  13. DataObjects::Mysql.logger = DataObjects::Logger.new(STDOUT, 0)
  14.  
  15. class Contact
  16. include DataMapper::Resource
  17.  
  18. property :id, Serial
  19. property :type, Discriminator
  20. property :name, String
  21.  
  22. has n, :notes
  23. end
  24.  
  25. class Company < Contact
  26.  
  27. end
  28.  
  29. class Person < Contact
  30.  
  31. end
  32.  
  33. class Note
  34. include DataMapper::Resource
  35.  
  36. property :id, Serial
  37. property :body, Text
  38.  
  39. belongs_to :contact
  40. end
  41.  
  42.  
  43. Contact.auto_migrate!
  44. # See that it creates contact_id;
  45. # => CREATE TABLE `contacts` (`contact_id` INT(11), `id` INT(11) NOT NULL AUTO_INCREMENT, `type` VARCHAR(50), `name` VARCHAR(50), PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci
  46.  
  47. Note.auto_migrate!
  48.  
  49. company = Company.create(:name => "Enron")
  50. note = Note.create(:contact => company, :body => "This is a note")
  51.  
  52. puts "reloading company and trying to access notes"
  53. company = Company.first
  54. # => SELECT `contact_id`, `id`, `type`, `name` FROM `contacts` WHERE `type` = 'Company' ORDER BY `id` LIMIT 1
  55. puts company.notes.inspect
  56. # => SELECT `contact_id`, `id`, `type`, `name` FROM `contacts` WHERE `contact_id` = 1 ORDER BY `id`
  57.  
  58. puts "reloading note and trying to access company"
  59. puts Note.first.contact.inspect
  60. # Works as expected
Add Comment
Please, Sign In to add comment